C - Does freeing an array of pointers also free what they're pointing to?

Laefica picture Laefica · Oct 16, 2015 · Viewed 23.3k times · Source

Say I have an array of pointers to structs that contain a string each and so for something like this:

printf("%s\n", array[0]);

The output is:

Hello.

If I perform a free(array) will this free what array[0] is pointing to? ("Hello.").

I've spent hours attempting to manually free each element and all I get is crashes. I'm hoping this is a shortcut :/

Answer

Paul Ogilvie picture Paul Ogilvie · Oct 16, 2015

This all depends on how the array was allocated. I'll give examples:

Example 1:

char array[10];
free(array);     // nope!

Example 2:

char *array;
array= malloc(10);   // request heap for memory
free(array);         // return to heap when no longer needed

Example 3:

char **array;
array= malloc(10*sizeof(char *));
for (int i=0; i<10; i++) {
    array[i]= malloc(10);
}
free(array);        // nope. You should do:

for (int i=0; i<10; i++) {
    free(array[i]);
}
free(array);

Ad. Example 1: array is allocated on the stack ("automatic variable") and cannot be released by free. Its stack space will be released when the function returns.

Ad. Example 2: you request storage from the heap using malloc. When no longer needed, return it to the heap using free.

Ad. Example 3: you declare an array of pointers to characters. You first allocate storage for the array, then you allocate storage for each array element to place strings in. When no longer needed, you must first release the strings (with free) and then release the array itself (with free).