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

大憨熊 提交于 2020-01-06 15:40:51

问题


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?


回答1:


  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.



来源:https://stackoverflow.com/questions/19885079/ansi-c-dynamic-memory-allocation-and-when-exactly-we-should-free-the-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!