If I allocated memory in my C program using malloc
and now I want to exit, do I have to free the allocated memory, or can I assume that since my entire program terminates, it will be freed by the OS?
I run in Linux environment.
It is not mandatory, but it can have benefits (as well as some drawbacks). If the program allocates memory once during its execution time, and would otherwise never release it until the process ends, it may be a sensible approach not to release the memory manually and rely on the OS.
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.
If free() is not used in a program the memory allocated using malloc() will be de-allocated after completion of the execution of the program (included program execution time is relatively small and the program ends normally).
It means that whenever you declare a regular variable of any data type in C, the programming language itself is responsible for deallocating or releasing this memory once your program has been executed successfully.
Any modern operating system will clean up everything after a process terminates, but it's generally not a good practice to rely on this.
It depends on the program you are writing. If it's just a command line tool that runs and terminates quickly, you may not bother cleaning up. But be aware that it is this mindset that causes memory leaks in daemons and long-running programs.
It can be a good design and very efficient to simply exit and allow the operating system to clean everything up. Apple OS X now does this by default: applications are killed without notice unless the application sets a "don't kill me" flag.
Often, freeing every memory allocation takes significant time. Some memory pages may have been swapped out and must be read back in so they can be marked as free. The memory allocator has to do a lot of work updating free memory tracking data. All of this effort is a waste because the program is exiting.
But this must be done by design and not because the programmer has lost track of allocated memory!
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