Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patterns for freeing memory in C?

I'm currently working on a C based application am a bit stuck on freeing memory in a non-antipattern fashion. I am a memory-management amateur.

My main problem is I declare memory structures in various different scopes, and these structures get passed around by reference to other functions. Some of those functions may throw errors and exit().

How do I go about freeing my structures if I exit() in one scope, but not all my data structures are in that scope?

I get the feeling I need to wrap it all up in a psuedo exception handler and have the handler deal with freeing, but that still seems ugly because it would have to know about everything I may or may not need to free...

like image 652
Abignale Avatar asked Mar 28 '09 03:03

Abignale


2 Answers

Consider wrappers to malloc and using them in a disciplined way. Track the memory that you do allocate (in a linked list maybe) and use a wrapper to exit to enumerate your memory to free it. You could also name the memory with an additional parameter and member of your linked list structure. In applications where allocated memory is highly scope dependent you will find yourself leaking memory and this can be a good method to dump the memory and analyze it.

UPDATE: Threading in your application will make this very complex. See other answers regarding threading issues.

like image 137
ojblass Avatar answered Oct 31 '22 23:10

ojblass


You don't need to worry about freeing memory when exit() is called. When the process exits, the operating system will free all of the associated memory.

like image 28
Michael Avatar answered Oct 31 '22 22:10

Michael