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.
Yes, all memory is returned.
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.
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.
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.
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.
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