What REALLY happens when you don't free after malloc?
Is freeing allocated memory needed when exiting a program in C
During my first C class, it was drilled into me that I should call
calloc() as it releases the space after dynamically allocating memory or otherwise it will be gone (I assume until system reboot). However, recently I started reading on various coding sites that this memory will be released back when the program ends.
Which one is the correct statement?
I would look in the official spec, but I have no idea where to get it (tried Googling).
Really short answer..
Both of the statements are correct.
A longer more elaborate one..
Both of them are correct, when your application fully terminates the allocated memory will (probably) be released back to the system.
I wrote "probably" since all modern/widely-used OSes will deallocate the memory used, but some primitive systems might not have this "feature" available.
Because of the above you should always use
free to deallocate memory of allocated but unused variables, especially during run-time (otherwise you'll have a memory leak that might/will slowly eat up all available memory).
If you wanna live on the wild side and not deallocate memory before the application terminates, that's fine by me and most people.B ut, please make sure that the platform you are going to run the application in really does release the memory back to the operating system afterwards.
Regarding looking in the standard ("official spec")
The standard most often/always leaves out implementation details, therefor there is nothing in there saying what will happen to allocated memory that hasn't been deallocated when the running application terminates.
That's implementation specific, and therefor depends in/on/at what you are running it.
On any system with protected memory (e.g. Windows 4.x+, Linux, Unix, …), the memory is released when the program terminates.
Some embedded systems may not always do so, however.
Regardless, it's definitely good form to
free() everything correctly.
This is valid within the program, that's while the process is running.
Out of it, this is OS dependent. There is no spec, but the big majority of systems will clean up all the memory used by the process after it is finished.
All memory for a given process is released back to the system at its termination. However, before a program exits, it's important to always
free() your memory, especially for long-running programs. In short-running programs, it's still good practice. It's always nice when
valgrind spits out a clean bill of health!