简体   繁体   中英

Can std::exit leak memory?

To answer my question, I conducted some tests:

(to replicate following includes are necessary)

#include <cstdlib>
#include <memory>

I made a function that called std::exit , with a std::unique_ptr in the main function.

void some_function()
{
    std::exit(EXIT_SUCCESS);
}

int main()
{
    std::unique_ptr<int> relying_on_raii{new int{5}};
}

If I called some_function after the unique_ptr declaration, memory might leak.

The two logs I got from Dr. Memory differed in the following line:

1 potential leak(s) (suspected false positives)
        […]
    6 unique,     6 total,    797 byte(s) of still-reachable allocation(s)

vs.

1 potential leak(s) (suspected false positives)
        […]
    7 unique,     7 total,    801 byte(s) of still-reachable allocation(s)

As can be seen, in the second example a 7th potential leak occured, which was 4 bytes in size, which is exactly the size of an int . When I repeated this test with double, it indeed turned out to be 805 byte(s) in the test with std::exit .

So is std::exit a safe function to use, or should you always return from main to prevent memory leaks?

So is std::exit a safe function to use, or should you always return from main to prevent memory leaks?

Yes, it can leak memory.

That's the less worrisome problem though. The more important problem will be if your program acquired resources that could not be released by shutting down the process. To handle such cases, it is better to either return with some error state until you are able to exit from main or use try-throw-catch to make sure that main is able to catch all uncaught exceptions and exits gracefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM