Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C malloc() memory space released after program ends? [duplicate]

Tags:

c

malloc

free

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.

like image 622
jn1kk Avatar asked Sep 19 '25 05:09

jn1kk


1 Answers

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.

like image 179
Filip Roséen - refp Avatar answered Sep 22 '25 04:09

Filip Roséen - refp