Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

free

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 :/

like image 685
Laefica Avatar asked Oct 16 '15 12:10

Laefica


People also ask

How do you free up an array?

Hence, to free up the memory at the end of the program, we must remove/deallocate the memory bytes used by the array to prevent wastage of memory. If the array is declared statically, then we do not need to delete an array since it gets deleted by the end of the program/block in which it was declared.

Can a pointer can point to an array?

Pointer to an array points to an array, so on dereferencing it, we should get the array, and the name of array denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it points.

What is array and Pointer in C programming?

A normal array stores values of variables, and pointer array stores the address of variables. Capacity. Usually, arrays can store the number of elements the same size as the size of the array variable. A pointer variable can store the address of only one variable at a time.

How do you declare an array in C?

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100};


1 Answers

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

like image 108
Paul Ogilvie Avatar answered Sep 21 '22 23:09

Paul Ogilvie