Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to the malloc'ed memory when exit(1) is encountered?

In C, if I allocate a memory using malloc and during the execution, the program encounters an exception/error and exits with a manually incorporated exit(1) statement in the program, does C compiler automatically frees the memory before making the unexpected exit or do I have to manually do this just before the exit(1) line in the program.

I use the gcc-4.5.2 compiler on Ubuntu 32bit platform.

like image 286
Abhinav Avatar asked May 14 '12 17:05

Abhinav


People also ask

Does Exit 1 free memory?

Yes, all memory is returned.

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.

What happens to Unfreed memory in C?

It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with a default garbage value.

Is malloc deallocated automatically?

In this article, we would be discussing the deallocation of memory without using free() method. But before getting into alternatives to free() let's see what is free() method. The "free" method in C is used to deallocate memory dynamically. The memory allocated by malloc() and calloc() is not automatically deallocated.


1 Answers

Once you call exit, OS takes all the allocated memory back. So no need to call free.

Edit: But It's generally good practice to free memory you allocated in your program as you may overlook it the call to free when you modify it in the future.

like image 187
P.P Avatar answered Sep 30 '22 16:09

P.P