Possible Duplicate:
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 free()
after malloc()
or 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).
Thanks.
Both of the statements are correct.
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.
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.
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