Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C free and struct

My question is about C free() function for deallocating memory blocks previously allocated with malloc().
If i have a struct data type compose of several pointers, each of them pointing to different memory locations, what would happen to those memory locations if i apply free() on the struct? will that locations be free too? or just the memory block that allocate the pointer?

like image 710
Leandro Galluppi Avatar asked Jul 16 '11 22:07

Leandro Galluppi


People also ask

Do I need to free pointer in struct?

You have to free the struct if you allocated it dynamically. You have to free its members before deallocating the struct if you allocated the members dynamically and don't have a reference to them anywhere else. From your example, yes, you need to free() l.

How do I free a struct pointer?

free() is a function which takes in a pointer. &x is a pointer. This code may compile, even though it simply won't work. If we pretend that all memory is allocated in the same way, x is "allocated" at the definition, "freed" at the second line, and then "freed" again after the end of the scope.

Should I free Strings in C?

Concrete answer: This assigns a pointer to a constant string to your char* a , by doing so you loose the pointer to the memory allocated in the first line, you should never free constant strings.

What happens when free in C?

free() just declares, to the language implementation or operating system, that the memory is no longer required.


1 Answers

No. They won't be freed. You have to free them "manually". The malloc knows nothing about the content of your struct (it does not know it is a struct at all, it is just a "piece of memory" from its point of view).

like image 62
ShinTakezou Avatar answered Sep 24 '22 10:09

ShinTakezou