When running the following code, I see the memory consumption of the process grow. Is there a memory leak in my code, is there a memory leak in the std implementation, or is it intended behaviour? It's running on a Windows 10 machine; both Visual Studio and the task manager show approximately 1MB memory growth per minute.

for (int i = 0; i < 10000; i++) {

    std::exception_ptr exptr = nullptr;
    std::string errmsg = "some error";
    try {
        throw std::runtime_error(errmsg.c_str());
    }
    catch (...) {
        exptr = std::current_exception();
    }

    if (exptr) {
        try {
            rethrow_exception(exptr);
        }
        catch (std::exception const& ex) {
            exptr = nullptr;
            std::cout << ex.what() << std::endl;
        }
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(10ms));
}

When directly throwing and logging without delay (without using std::exception_ptr), the memory consumption doesn't grow. std::exception_ptr is advertised as behaving like a smart pointer, so when resetting it (setting it to nullptr), the underlying resource should be destroyed. Therefore, I expect the underlying exception to be freed appropriately.

1

There are 1 best solutions below

0
On

I have found out the following: when i copy the code into a fresh project, the memory consumption doesn't grow. I compared the compiler options, and the following compiler option needs to be activated to avoid growing memory consumption: /EHsc

From the msvc compiler documentation i read: [...]The default exception unwinding code doesn't destroy automatic C++ objects outside of try blocks that go out of scope because of an exception. Resource leaks and undefined behavior may result when a C++ exception is thrown.[...] So the growing memory consumption probably was a memory leak.