I am trying to get my head around memory allocations and freeing them in ANSI C. The problem is I don't know when to free them.
1) Does program exit free the allocated memory itself (even if I didn't do it by free()
)?
2) Let's say my code is something like this: (please don't worry about the full code of those structs at the moment. I am after the logic only)
snode = (stock_node *) realloc(snode, count * sizeof(stock_node));
struct stock_list slist = { snode, count };
stock_list_ptr slist_ptr = (stock_list_ptr) malloc(sizeof(stock_list_ptr));
slist_ptr = &slist;
tm->stock = slist_ptr;
So above; snode goes to stock_list and stock_list goes to slist pointer and it goes to tm->stock.
Now, as I have assigned all of them to tm->stock at the end, do I have to free snode and slist_ptr? Because tm struct will be used in rest of the program. If I free snode and slist_ptr will tm struct lose the values?
Yes, when the program exits, the process exits, and the OS reclaims the stack and heap space allocated to that process. Imagine how bad it would be if the OS could not take back unallocated memory from crashed processes!
As a general rule of thumb, for every malloc()
(or calloc()
or — with caveats — realloc()
) in a program, there should be a corresponding free()
. So in short you need to at some point free both the space associated with snode
and the space associated with slist_ptr
.
In this particular instance, you've actually managed to create for yourself a memory leak. When you do the malloc()
for slist_ptr
, you allocated 4 bytes (8 bytes on 64-bit) for that pointer. On the next line, you reassign slist_ptr
to point to the location of slist
, which means you no longer have a pointer to the space you allocated for slist_ptr
.
If you did call free on tm->stock
, you would thus free the space associated with the initial realloc
(be sure you mean realloc
and not malloc
), but you still are leaking due to the malloc
for slist_ptr
.