Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

malloc - ANSI C Dynamic Memory Allocation and when exactly we should free the memory

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. 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!

  2. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...