When a program terminates what happens to the memory allocated using malloc that is not free'ed?

倖福魔咒の 提交于 2019-11-29 05:42:41

The other answers tell you the two important things:

  1. Yes, the memory is reclaimed by the OS, so you don't technically need to free() it.
  2. It's good practice to free everything you malloced anyway.

However, it's important to say why it's good practice to free() everything you've malloced. In my view:

  1. Habit: If you get in the habit of freeing whenever you've malloced, you won't accidentally forget when a memory segment isn't around for the lifetime of the program.
  2. Maintainability: If someone comes along to refactor your program so that a segment of memory is no longer around for the lifetime of the program, the presence of cleanup code in the original will mean that it's very likely that the refactored version also includes the cleanup code. For me, this is the most important reason.
  3. Debugging: If we expect that all memory is cleaned up correctly, then spotting memory that's actually leaking is much easier.

O.S. will reclaim the memory not free'd up.

But is a good practice to free all memory allocated by malloc

The memory is reclaimed by the Operating system once your program exits.
The OS doesn't understand that your program leaked memory, it simply allocates memory to the program for running and once the program exits it reclaims that memory.

However, other resources like file descriptors may/may not be recalimed by the OS causing a resource leak.

So it is a good practice that a program should cleanup all the resource it utilized before exiting.

When a process allocates memory dynamically, it borrows block(s) of memory from OS. When a process doesn't need allocated memory it free(s). Then OS adds those blocks to its free list. The same happens when a process terminates. All the blocks used by the process is reclaimed by the OS.

Read memory-management for more info.

More importantly, FREE ensures the sanity of the memory/buffers allocated by you, and hence forth exsisting a good checkpoint for curbing/catching up heap corruption.

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