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

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).


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

No they don't get freed automatically, but depending on how you allocated each of them, there might be no need to free them actually. You would only need to free them if they point to memory which was returned by malloc and similar allocation functions.

Say you have array of pointers to string array

char * array[2];
array[0] = "Some text"; // You would not need to free this
array[1] = malloc(LENGTH); // This one you would have to free

Note in this case you don't need to free the array itself. Only the element with index 1.


You only ever need to free what you manually malloc(). So no, depending on the pointer it might not, and might not even be necessary.

Tags:

C

Free