Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the heap get freed when the program exits? [duplicate]

Tags:

c

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?

like image 308
Andrew Legacci Avatar asked Apr 08 '13 15:04

Andrew Legacci


People also ask

Is heap memory automatically freed?

Unlike stack memory, heap memory is allocated explicitly by programmers and it won't be deallocated until it is explicitly freed.

Is memory freed when a program exits?

In all modern OS's, such as Linux, MacOS and Windows, memory is automatically freed when the application exits.

Does the heap memory gets deallocated after program execution?

An object in heap memory can be passed back to the caller of a function, since it is not deallocated when that function exits.

What happens to the allocated memory after a program 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.


2 Answers

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.

like image 114
75inchpianist Avatar answered Sep 28 '22 22:09

75inchpianist


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.

like image 37
Michael Greene Avatar answered Sep 28 '22 23:09

Michael Greene