Suppose I malloc some memory into some pointers but don't free them before the program exits. Does this memory get freed automatically on exit or will the memory leak continue to be there till I restart the computer?
Unlike stack memory, heap memory is allocated explicitly by programmers and it won't be deallocated until it is explicitly freed.
In all modern OS's, such as Linux, MacOS and Windows, memory is automatically freed when the application exits.
An object in heap memory can be passed back to the caller of a function, since it is not deallocated when that function exits.
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.
The answer is, most often.
Freeing the heap is responsiblity of the OS. While most OS (especially mainstream OS) frees the heap upon exit, it is not necessarily true of say embedded system OS.
When you call for memory to be allocated on the heap, a system call is made to the kernel space of the OS to provide this memory. This memory is mapped to your process structure, which is maintained by the OS. When your program exits, the OS goes through a clean up routing, closing all file descriptors, and marks this memory free for allocation to other processes (among other things).
Some of these answers are incorrect in saying that it is compiler dependant. The compiler does not say 'hey free all this memory on program exit'. That wouldn't make sense, what happens if the OS unexpectedly terminates the program then? No, the compiler is responsible for generating system calls whenever memory allocation/deallocation is explicitly requested for the heap.
Memory won't be freed by your program or libc, but will be freed by the operating system on all modern operating systems. They assign memory to specific processes and clean up the memory when the process terminates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With