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

前端 未结 7 2007
眼角桃花
眼角桃花 2020-12-29 15:28

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 t

7条回答
  •  醉梦人生
    2020-12-29 15:42

    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.

    However, you should definitely clean things up, in particular if you have used any other types of resources:

    • Files created in temporary directories won't be deleted. This includes /dev/shm, leaving such a file could be considered a "memory leak".
    • System V or posix shared memory segments won't get thrown away when your process quits. If this bothers you, clean them up specifically. Alternatively, clean them up on a subsequent run.

    Normally a leak (of a persistent or semi-persistent object e.g. file) doesn't matter if a subsequent run doesn't leak more memory. So cleaning up on a future run is good enough.

    Imagine a process running every 5 minutes from "cron", if it crashes on each run and leaves some mess, it's still ok provided each run cleans up the mess from the previous crash.

提交回复
热议问题