Releasing memory that has been allocated to an array of char pointers (strings). Do I need to free each line or just the "main" pointer?

I have a function that takes a pointer to char ** and fills it with strings (an array of strings, I think). * list_of_strings * memory is allocated inside the function.

char * *list_of_strings = NULL; /* list_of_strings malloc'd inside function */ fill_strings_with_stuff(&list_of strings); use_list_for_something(list_of_strings); /* Now how do I free it all? */ 

How can I free memory after I used strings? If i call

 free(list_of_strings); 

won't just free the actual pointers, and not the memory that each line uses? How to completely free memory

Just for clarity, the function looks something like this:

 fill_strings_with_stuff(char *** list) { *list = malloc(AMOUNT); for (i = 0; i < SOMETHING; i++) { *(list + i) = malloc(LINE_LEN); *(list + i) = some_string_from_somewhere } /* ... */ } 
+4
source share
4 answers

won't just free the actual pointers, and not the memory that each line uses?

Yes indeed.

How to completely free memory

Looping an array and freeing each row one by one before freeing the array itself. For instance.

 for (i = 0; i < SOMETHING; i++) { free(list[i]); } free(list); 
+16
source

Basically, there is a rule for allocation and release: you need to call as many free () as you call malloc (). It is so simple. In any other case, you have a memory leak.

+6
source

Yes, you should free() get every block obtained from malloc() . You do this by moving the array of pointers and calibrating free() for each element and only then freeing the array itself.

Only you know that there is a tree structure that can be recursively freed, that knowledge is nowhere in the C run-time heap, so the heap manager does not know about it, and your program should free everything.

+2
source

You need to iterate over list and call free() for each member of the array. Then free the array.

+2
source

Source: https://habr.com/ru/post/1336112/


All Articles