Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid memory leak when user press ctrl+c under linux?

Tags:

c

memory-leaks

In my program written with C and C++, I will new an object to fulfill the task, then delete the object.

At the moment after new object but before delete object, if the user presses ctrl+c to break the process, that will cause delete not to be called and a memory leak occurs.

What should I do to avoid this situation?

Also, if the memory was reclaimed by the OS, what about the opened files? Are they closed by the OS or should I close them manualy?

like image 494
PDF1001 Avatar asked Jan 26 '11 00:01

PDF1001


People also ask

Does Ctrl C free memory?

If the process quits, a memory leak will NOT normally occur. Most of the memory you allocate will be freed on Ctrl+C. If you see memory usage not return to its prior level, it is almost certainly caused by buffered filesystem blocks.

Does Linux have memory leaks?

A lot of programs on Linux are written in C, some C++, and those languages don't have garbage collection so they are prone to these memory leaks. Memory leaks can be a big deal. They can really slow down your system.

Why memory leak happens in C?

In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.


2 Answers

In a virtual-memory-based system, all memory is returned to the OS when a process is terminated, regardless of whether it was freed explicitly in the application code. The same might not be true of other resources, however, which you may want to free cleanly. In which case, you need to provide a custom signal handler for the SIGINT signal (which is received on Ctrl+C), see e.g. http://linux.die.net/man/2/sigaction.

like image 122
Oliver Charlesworth Avatar answered Sep 30 '22 17:09

Oliver Charlesworth


Pressing CtrlC will send a SIGINT to the process, which by default does a mostly-orderly shutdown, including tearing down the memory manager and releasing all allocated heap and stack. If you need to perform other tasks then you will need to install a SIGINT handler and perform those tasks yourself.

like image 27
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 18:09

Ignacio Vazquez-Abrams