Search code examples
c++memory-leaksshared-ptr

How memory leak can happen in this code


Here I read an example which can leak memory

void foo(std::shared_ptr<int> p, int init)
{
  *p = init;
}
foo(std::shared_ptr<int>(new int(42)), seed()); // assume seed() returns an int

The article says if seed() throws, then there will be a memory leak. I am not understanding how?

If the shared_ptr is created first, and then seed() throws an exception, during stack unwinding, the temporary shared-ptr will be destroyed, deallocating the memory. If seed() throws error beforehand, then there will be no allocation at the first place.

What I am missing?


Solution

  • the order of execution can be

    auto temp = new int(42);
    auto temp2 = seed(); // if throw exception, temp is leaked
    auto temp3 = std::shared_ptr<int>(temp);
    foo(temp3, temp2);