Does the heap persist when the program exits?

Suppose that malloc has some memory in some pointers, but do not free them until the program exits. Does this memory automatically delete on exit or will the memory leak continue until the computer restarts?

+7
source share
6 answers

The answer is most often.

Freeing up the heap is the responsiveness of the OS. Although most OS (especially the main OS) frees up a bunch on exit, this does not necessarily apply to the embedded system OS.

When you call memory allocation in a heap, a system call is made for the kernel space of the OS to provide that memory. This memory maps to your process structure, which is supported by the OS. When your program exits, the OS goes through a clean routing, closing all file descriptors and placing this memory for free for allocation to other processes (by the way).

Some of these answers are incorrect, saying that they depend on the compiler. The compiler does not say "free all this memory at the output of the program." It makes no sense, what happens if the OS unexpectedly terminates the program? No, the compiler is responsible for generating system calls whenever memory allocation / deallocation is explicitly requested for the heap.

+6
source

The memory will not be freed by your program or libc, but it will be freed by the operating system on all modern operating systems. They assign memory to specific processes and clear memory when the process ends.

+2
source

Any modern desktop operating system will recover resources upon exiting the process. There will be no memory leak.

+1
source

It depends on which OS you are using. Obviously, any modern desktop OS is designed to clean up after you when your program exits, if necessary.

+1
source

If you look at the C standard, this is a specific implementation, so you cannot be sure of that.

But most operating systems will free up memory after the process is completed, but this may not be the case on some smaller / simpler platforms.

+1
source

It's not a question. How the heap is implemented depends on the compiler and what os does after the program exits. As far as I know, all modern free memory resources when exiting the program. This may not be true for some embedded systems or drivers.

+1
source

All Articles