Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: malloc error-pointer being freed was not allocated

Tags:

c

malloc

I am trying to return an array of string from a function and then free the memory it used. The code is below:

int main(int argc, const char * argv[])
{
    for (int m = 0; m < 10000; m++) {
        char **data = dataTest();

        int i = 0;
        while(data[i]) {
            printf("%p ",data[i]);
            free(data[i]);
            i++;
        }
        printf(" address= %p.\n",data);
        free(data);
    }

    return 0;
}

Here is the function:

char **dataTest()
{
    char *row[] = {"this", "is", "a", "data", "string", NULL};
    char **str = row;
    char **dataReturn = (char **) malloc(sizeof(char *) * 6);

    int i = 0;
    while (*str) {
        dataReturn[i] = malloc(sizeof(char) * strlen(*str));
        strcpy(dataReturn[i++], *str);
        str++;
    }

    return dataReturn;
}

It runs well in the beginning, but soon the error occurs. Below is the result. The address goes wrong somehow and the malloc error happens. Anyone has met the same problem before?

0x100300030 0x100300040 0x100300050 0x100300060 0x100300070  address= 0x100300000.
0x100300030 0x100300040 0x100300050 0x100300060 0x100300070  address= 0x100300000.
0x100400030 0x100300030 0x100300040 0x100300050 0x100300060  address= 0x100400000.
testC(562,0x7fff73e71310) malloc: *** error for object 0x3000000000000:     
pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
0x100300060 0x100300070 0x100300030 0x100300040 0x100300050 0x3000000000000                 
Program ended with exit code: 9
like image 821
ButterLover Avatar asked Feb 10 '23 14:02

ButterLover


1 Answers

You need to add this to just before return dataReturn; in your dataTest function:

dataReturn[i] = NULL ;

otherwise your while (data[i]) {} will continue further than wanted.

And instead of:

dataReturn[i] = malloc( sizeof(char) * (strlen(*str)) );

write:

dataReturn[i] = malloc(strlen(*str) + 1);

in order to allocate space for the terminating zero.

BTW sizeof (char) is always 1.

like image 108
Jabberwocky Avatar answered Feb 12 '23 02:02

Jabberwocky