天天看點

linux C語言:*** glibc detected *** ./control: free():invalid pointer:

前言

今天遇到了一個問題,折騰好久才找到問題原因,永遠不要理想化,各種困難都會浮現的,我們隻需要不驕不躁,一定可以解決所有問題。

問題代碼

我們先來看一下問題代碼部分吧。

static char *control_process(char *verb[],char *noun[],char *result)
{
    int verbOpcode = 0; //verb Opcode index
    int nounOpcode = 0; //noun Opcode index 
    char *Matchverb = (char *)malloc(40*sizeof(char));
    char *Matchnoun = (char *)malloc(40*sizeof(char));
    char *Playfile = (char *)malloc(sizeof(char)*40);
    int index1 = 0;
    printf("enter the control_process \n\n");
    for(index1 =1; index1 <37;index1++)
    {    
        Matchverb = mystrstr1(result,verb[index1]);
        if(Matchverb != NULL)
        {
            verbOpcode = index1;
            break;
        }else
        {
            verbOpcode = 0;
        }
    }
    int index2 = 0;
    for(index2 = 1;index2 <29;index2++)
    {
        Matchnoun = mystrstr1(result,noun[index2]);
        if(Matchnoun != NULL)
        {
            nounOpcode = index2;
            break;
        }else
        {
            nounOpcode=0;
        }
    }
    printf("achieve the verb and noun deal \n\n");
    sprintf(Playfile,"/mnt/card/1%02d2%02d",verbOpcode,nounOpcode);
    printf("play file is %s  \n\n",Playfile);
    free(Matchverb);
    free(Matchnoun);
    return Playfile;
    
}      

解決問題

就是這段代碼,一直報錯,初看确實看不到什麼問題,為此我加了很多列印,最後确定問題就發生在 free(Matchverb);free(Matchnoun);這兩句話,下面就講一個一知識點,為什麼free發生異常了呢?

我們在使用malloc配置設定記憶體後,指針變量擷取到了位址。但是在程式中我們又給指針變量重新指派了,是以位址發生了變化,此時我再次使用free()來釋放,已經不是原來malloc配置設定的記憶體位址了,是以這就是指針位址非法。

修改方法

static char *control_process(char *verb[],char *noun[],char *result)
{
    int verbOpcode = 0; //verb Opcode index
    int nounOpcode = 0; //noun Opcode index 
    char *Matchverb = (char *)malloc(40*sizeof(char));
    char *Matchnoun = (char *)malloc(40*sizeof(char));
    char *Playfile = (char *)malloc(sizeof(char)*40);
    char *p1 = Matchverb;
    char *p2 = Matchnoun;
    int index1 = 0;
    printf("enter the control_process \n\n");
    for(index1 =1; index1 <37;index1++)
    {    
        Matchverb = mystrstr1(result,verb[index1]);
        if(Matchverb != NULL)
        {
            verbOpcode = index1;
            break;
        }else
        {
            verbOpcode = 0;
        }
    }
    int index2 = 0;
    for(index2 = 1;index2 <29;index2++)
    {
        Matchnoun = mystrstr1(result,noun[index2]);
        if(Matchnoun != NULL)
        {
            nounOpcode = index2;
            break;
        }else
        {
            nounOpcode=0;
        }
    }
    printf("achieve the verb and noun deal \n\n");
    sprintf(Playfile,"/mnt/card/1%02d2%02d",verbOpcode,nounOpcode);
    printf("play file is %s  \n\n",Playfile);
    Matchverb = p1;
    Matchnoun = p2;
    free(Matchverb);
    free(Matchnoun);
    return Playfile;
    
}