user2861799
user2861799

Reputation: 225

what happens to malloc?

Well I think I know the answer to the question but I rather be assured. If you malloc memory on the heap and exit the program before you free the space does the os or compiler free the space for you ?

Upvotes: 3

Views: 203

Answers (3)

Paulo Bu
Paulo Bu

Reputation: 29804

The OS free the space for you when it removes the process's descriptor (task_struct in Linux's case) from its process list.

The compiler usually generates an exit() system call and there's where all this is handled.

On Linux, basically, all these happens in the kernel's exit_mm() function, eventually invoked by exit(). It will release the address space owned by the process with mm_release() function. All that source is available for you to read (although it might get a little complicated :) But yes, the operating system is in charge of releasing process's resources.

And just because I like it so much, if you're into these topics, this is a very GOOD reading: Understanding the Linux Kernel.

Upvotes: 3

Lundin
Lundin

Reputation: 215360

That is outside the scope of the C standard. What happens depends on the system. On all common mainstream operative systems, the OS will free the memory when the process is done.

Still, it is good practice to always clean up your own mess. So no matter what the OS does, you should always free up all resources you were using. Doing so is also an excellent way to spot hidden runtime bugs: if you have bugs, the program might crash when you try to free the resources and thereby alerting the programmer of the bugs.

As for the compiler, it is only active during program creation, it has absolutely nothing to do with the runtime execution of your program.

Upvotes: 3

Brian Agnew
Brian Agnew

Reputation: 272437

The OS will clear all resources consumed by your program, including all allocated memory, network connections, filehandles etc.

Upvotes: 1

Related Questions