且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ANSI C动态内存分配,当正是我们应该释放内存

更新时间:1970-01-01 07:59:42


  1. 是的,当程序退出时,进程退出,操作系统收回分配给该进程栈和堆空间。试想一下,如果不好操作系统无法从崩溃进程收回未分配的内存这将是!


  2. 根据经验,一般情况下,每的malloc()(或释放calloc()或 - 带警告 - 在程序的realloc()),应该有一个相应的免费()。因此,在短期,你需要的在某一点的***都与 snode 相关联的空间和 slist_ptr 相关的空间code>。


在这个特殊的情况下,你实际上已经成功地为自己创建一个内存泄漏。当你做了的malloc() slist_ptr ,你分配4个字节为(8字节64位)指针。在下一行,重新分配 slist_ptr 来指向 SLIST 的位置,这意味着你不再有一个指针以空间为您 slist_ptr 分配的。

如果你没有拨打免费 TM->股份,你将因此***与初始相关的空间的realloc (确保你的意思是的realloc ,而不是的malloc ),但你仍然是由于的malloc 为 slist_ptr

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