简体   繁体   中英

Free() a partially freed array of strings C

Assume that I have an array of strings, some of which are already free'd, as an example:

char **array;
array = malloc(20*sizeof(char*));

for(i=0;i<arr_size;i++)
{
    array[i]='\0';
    free(array[i]);
}
free(array);

Is this a correct way to do it? Because I still seem to get some memory leaks, in my case an array of 20 strings where 9 are already freed.

I guess the question is how to go about freeing "freed" strings. Thanks for the help!

I guess the question is how to go about freeing "freed" strings.

Well, you don't. You must free every malloc 'ed string exactly once. Calling free several times on the same string will lead to undefined behaviour.

That aside, your problem is the following:

array[i]='\0';

Here, you are overwriting the value of the pointer before you free it.

By convention, you should always set a pointer to NULL after free -ing. Then you should check to see if the pointer is NULL , if not, then you can free . That way you can keep track of which ones have been free -ed and which ones haven't.

1 malloc() allocation requires just 1 free() to deallocate memory. So free(array); is sufficient to deallocate the memory.

free() deallocating memory is counter to allocated memory dynamically using malloc() .

Using free(array[i]); will cause problems / strange errors as you are trying to free a pointer whose value (pointer) you have changed on the previous line.

The code array[i]='\\0';

may not have the desired results as it is setting the pointer value not the character contents. Perhaps sprintf(array[i],"\\0"); would be better

char **array=NULL;  //(Helps you to give it an initial value pointing to NULL)

array = malloc(arr_size+1);  

if (!array[i])
{
// array == NULL which is not right after malloc
// there has been an error with malloc, trap and exit somehow
}
else
{
// Use array as you wish as it has been allocated, take care not to 
// run past the end of the array length
}

if (array[i]) free(array[i]);   // checks that it is not NULL anymore, as NULL does not need freeing.

You could expand the IF statement to: (means that same as above, but includes forcing a freed variable to NULL)

if (array[i]!=NULL) 
{
 free(array[i]);   
 array[i] = NULL;
}

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