Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heap memory clearance when application closes abruptly

As we know the heap is used for dynamic allocation of memory for an application. How is the heap memory cleared(and hence avoiding memory leaks) in case of abnormal application termination?

Consider the following scenarios:

  • Say an application crashes all of a sudden on Windows or Linux.
  • We force kill an application in linux: kill -9 <process_name>
  • A C++ program in Visual Studio throws an error in the middle of execution.

Is heap management and cleanup any different in the above cases? [Please add more use-case scenarios which might be of interest here]

This question came up in my mind since we always talk about ensuring no memory leak happens in our code. Now how do we handle scenarios where we force close an application which might result into a program exit without calling the memory free-up calls.

And if such memory leak happens repeatedly, is it possible that the OS becomes short of heap memory? Or does the OS have a way of handling it...

like image 707
Vishal Avatar asked Dec 27 '22 04:12

Vishal


1 Answers

Assuming the OS is a typical implementation of Unix or Windows, the heap memory is released by the OS when the application is killed, no matter what method it is killed by.

Obviuously, other OS's may not do exactly this, and it's up to each OS to solve this problem in a meaningful way - I'm not aware of any OS that doesn't "clean up after killed processes", but I'm sure such a thing may exist in some corner of this world.

Edit: There may be OTHER resoources that aren't quite so easily released, such as shared memory or semaphores used by multiple. But most OS's tend to deal with those by releasing the reference of the application being killed, and letting other processes that wait for any "waitable object" (mutex, semaphore, etc) will be "let run".

like image 118
Mats Petersson Avatar answered Dec 28 '22 19:12

Mats Petersson