简体   繁体   中英

C- How to free the following malloced memory

Can someone please help me on how to free the two dimensional array here. I tried using the loop to free but i get an error saying:

 *** glibc detected *** ./assignment4: free(): invalid pointer: 0x0932b196 ***

The thing is when i free the 0th element alone i dont get any problem. But when i free elements [1] to [7] i get the error.

char ** stringOne; 
stringOne = malloc(sizeof(char*)*8);

stringOne[0] = malloc(sizeof(char)*6);
stringOne[0] = strtok(listofdetails[0], " ");

for(i=1;i<8;i++)
{
    stringOne[i] = malloc(sizeof(char)*6);
    stringOne[i] = strtok(NULL, " ");
}

for(i=0;i<8;i++) // FREEING memory
{
    free(stringOne[i]);
}

The strtok function returns a pointer into the string you're tokenizing, and that pointer overwrites the pointer you previously allocate, leading you to lose the pointers to the allocated memory.

There are two solutions: Don't allocate memory (and don't free), or copy into the allocated memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM