deallocating memory when using exit(1), c++

血红的双手。 提交于 2019-12-10 17:42:52

问题


I am working on a school assignment, and we were told that whenever we have an input error we should print a message and exit the program. Obviously I use exit(1), but the problem is I have memory leaks when using this functions. I don't understand why - every single variable I've used was on the stack and not on the heap.

What should I do to prevent those memory leaks? Thanks!


回答1:


exit does not call the destructors of any stack based objects so if those objects have allocated any memory internally then yes that memory will be leaked.

In practice it probably doesn't matter as any likely operating system will reclaim the memory anyway. But if the destructors were supposed to do anything else you'll have a problem..

exit doesn't really mix well with c++ for this reason. You are better just allowing your program to return from main to exit, or if you need to exit from an internal function throwing an exception instead, which will cause the call stack to be unwound and therefore destructors to be called.




回答2:


When using the exit function, your program will terminate and all memory allocated by it will be released. There will be no memory leak.

EDIT: From your comments, I can understand you're concerned that your objects aren't destroyed before termination (i.e. their destructor isn't called). This however doesn't constitute a memory leak, since the memory is released by the process and made available to the system. If you're counting on object destructors to perform operations important to your workflow, I suggest returning an error code instead of using exit and propagate that error code up to main().

EDIT2:

According to the standard, calling exit() during the destruction of an object with static storage duration results in undefined behavior. Are you doing that?




回答3:


The solution is to not use exit() at all. You write your program using RAII (use classes for resources management) and throw an exception when something goes wrong. Then all memory is reclaimed thanks to destructors being called.




回答4:


You don't have a real memory leaks. When a program is terminate the OS freeing all the memory the program used.



来源:https://stackoverflow.com/questions/7414051/deallocating-memory-when-using-exit1-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!