使用 exit(1)、c++ 时释放内存
我正在做一项学校作业,我们被告知,每当我们有意见时 错误我们应该打印一条消息并退出程序。显然我使用 exit(1),但是 问题是我在使用这个函数时出现内存泄漏。我不明白为什么 - 我使用的每个变量都在堆栈上而不是在堆上。
我应该做什么来防止这些内存泄漏? 谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
exit 不会调用任何基于堆栈的对象的析构函数,因此如果这些对象在内部分配了任何内存,那么内存将会泄漏。
实际上,这可能并不重要,因为任何可能的操作系统都会回收内存。但如果析构函数应该做任何其他事情,你就会遇到问题..
由于这个原因, exit 并没有真正与 C++ 很好地混合。您最好只允许程序从 main 返回以退出,或者如果您需要从内部函数退出并抛出异常,这将导致调用堆栈展开并因此调用析构函数。
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.
当使用
exit
函数时,你的程序将终止,并且它分配的所有内存都将被释放。不会出现内存泄漏。编辑:
从您的评论中,我可以理解您担心您的对象在终止之前没有被销毁(即它们的析构函数没有被调用)。然而,这并不构成内存泄漏,因为内存由进程释放并可供系统使用。如果您依靠对象析构函数来执行对工作流程重要的操作,我建议返回错误代码而不是使用
exit
并将该错误代码传播到 main()。EDIT2:
根据标准,在销毁具有静态存储持续时间的对象期间调用 exit() 会导致未定义的行为。你在这样做吗?
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?
解决方案是根本不使用
exit()
。您使用 RAII(使用类进行资源管理)编写程序,并在出现问题时抛出异常。然后,由于调用了析构函数,所有内存都被回收。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.你没有真正的内存泄漏。当程序终止时,操作系统会释放该程序使用的所有内存。
You don't have a real memory leaks. When a program is terminate the OS freeing all the memory the program used.