jonteZ
jonteZ

Reputation: 23

c++ int pointer to array of pointers to arrays memory leaks

so I have this class with a functions.hpp and a functions.cpp

#include "function.hpp"

test::test(int size)
{
    this->size = size;
    matrix = new int*[this->size];
    for (int i = 0; i < size; i++)
    {
        matrix[i] = new int[this->size];
    }
}

test::~test()
{
    for (int i = 0; i < this->size; i++)
        delete[] this->matrix[i];
    
    delete[] this->matrix;
}

but this still produces memory leaks, I am using the CRT library to test this

#include "function.hpp"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    int size = 10;
    test test(size);
    _CrtDumpMemoryLeaks();
    return 0;
}

this code still dumps memory leaks on me, and I've followed several tutorials and I'm starting to doubt either the CRT library or my computer.

Upvotes: 2

Views: 65

Answers (1)

john
john

Reputation: 87959

The problem is that the destructor is not called until main is exited which is after you call _CrtDumpMemoryLeaks. Change your code to this

int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    {
        int size = 10;
        test test(size);
    }
    _CrtDumpMemoryLeaks();
    return 0;
}

The extra {} ensure that the destructor is called before the call to _CrtDumpMemoryLeaks.

A different techique would be to write a class to perform the check.

class LeakCheck
{
public:
    LeakCheck() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); }
    ~LeakCheck() { _CrtDumpMemoryLeaks(); }
    LeakCheck(const LeakCheck&) = delete;
    LeakCheck& operator=(const LeakCheck&) = delete;
};

int main()
{
    LeakCheck _checker;
    int size = 10;
    test test(size);
    return 0;
}

Because destructors are called in reverse order of constructors, it's guaranteed that _CrtDumpMemoryLeaks will be called after the destructor of test.

I want to call LeakCheck a shim class but apparantly that's not the right terminology, maybe someone can tell me the correct term in the comments.

Upvotes: 6

Related Questions