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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…