开发者

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

开发者 https://www.devze.com 2023-04-04 23:16 出处:网络
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 us开发者_如何学Goe exit(1), but

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 us开发者_如何学Goe 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!


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.


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消