在Linux下用户按ctrl + c时如何避免内存泄漏? [英] How to avoid memory leak when user press ctrl+c under linux?

查看:513
本文介绍了在Linux下用户按ctrl + c时如何避免内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在用C和C ++编写的程序中,我将新建一个对象以完成任务,然后删除该对象.

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

在新对象之后但在删除对象之前,如果用户按 ctrl + c 中断该过程,将导致不调用delete并导致发生内存泄漏.

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?

推荐答案

Ctrl C 将向进程发送SIGINT,默认情况下, -有序关闭,包括拆除内存管理器并释放所有分配的堆和堆栈.如果需要执行其他任务,则需要安装SIGINT处理程序并自己执行这些任务.

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.

这篇关于在Linux下用户按ctrl + c时如何避免内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆