Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When you exit a C application, is the malloc-ed memory automatically freed?

Let's say I have the following C code:

int main () {   int *p = malloc(10 * sizeof *p);   *p = 42;   return 0;  //Exiting without freeing the allocated memory } 

When I compile and execute that C program, ie after allocating some space in memory, will that memory I allocated be still allocated (ie basically taking up space) after I exit the application and the process terminates?

like image 536
Andreas Grech Avatar asked Feb 06 '10 15:02

Andreas Grech


People also ask

Is malloc automatically freed?

This will happen automatically. You do not need to write anything for this.

Is memory automatically freed when a program exits?

Most memory on most OSes however will be automatically reclaimed when the process exits.

Does exit free malloc?

Yes, all memory is returned.

Does C automatically deallocate memory?

No it doesn't clear. The malloc function will request a block of memory from the heap . You have to pass the pointer returned form malloc to the free function when is no longer needed which deallocates the memory so that it can be used for other purposes.


1 Answers

It depends on the operating system. The majority of modern (and all major) operating systems will free memory not freed by the program when it ends.

Relying on this is bad practice and it is better to free it explicitly. The issue isn't just that your code looks bad. You may decide you want to integrate your small program into a larger, long running one. Then a while later you have to spend hours tracking down memory leaks.
Relying on a feature of an operating system also makes the code less portable.

like image 74
Yacoby Avatar answered Oct 19 '22 12:10

Yacoby