How to avoid memory leak when user press ctrl+c un

2019-02-03 22:32发布

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?

7条回答
孤傲高冷的网名
2楼-- · 2019-02-03 23:10

When CTRL+C is pressed in a Linux console, the SIGINT signal is sent to the application which, if the signal has no handler, will terminate the program, returning all memory to the OS. This of course would make it pointless to do any freeing of memory, since all memory will freed once the program exists. However, if you would like to handle the CTRL+C SIGINT signal (maybe to write out some last data to a file or do some other cleanup), you can use the function signal() to install a function to be called when the signal is received. Check out the man page for this function if you want to learn more.

查看更多
登录 后发表回答