Search code examples
c++c++11memory-managementmemory-leaksshared-ptr

shared_ptr memory leak without delete operator


I have implemented a simple struct:

struct ListenerNode
{
    ListenerNode() : previous(nullptr), next(nullptr), listener(nullptr), once(false) {}
    std::shared_ptr<ListenerNode> previous;
    std::shared_ptr<ListenerNode> next;
    std::function<void(int)> listener;
    bool once;
};

And this is going to represent an entity in a scenegraph implementation. The wierd behavior that I am observing is that when I use the struct simply like:

int main(int argc, char** argv)
{
    ListenerNode n;
}

It leaks memory but when I use it like:

int main(int argc, char** argv)
{
    ListenerNode* n = new ListenerNode();
    delete n;
}

It does not leak memory! I don't understand what's going on here. I always thought making an instance of a class/struct without new calls the destructor immediately when the variable goes out of scope.

Could someone please explain to me what's going on here? I don't see any obvious reference increment neither.


Solution

  • According to your comment, you test for memory leak as in the following snippet:

    int main(int argc, char** argv) 
    {
        ListenerNode n;
        _CrtDumpMemoryLeaks();
    }
    

    In this case, at the time _CrtDumpMemoryLeaks() is called, n is not out-of-scope yet. You can definitely access the content of n after _CrtDumpMemoryLeaks() without any problem. n is destructed after the closing brace of main() is encountered.

    If you add an extra pair of braces:

    int main(int argc, char** argv) 
    {
        { ListenerNode n; }
        _CrtDumpMemoryLeaks();
    }
    

    Then, n is destructed right when the extra closing brace is encountered. At the time you call _CrtDumpMemoryLeaks(), n is not accessible at all since it's already out of scope.