user15822443
user15822443

Reputation:

I can't free the memory I declared in a class in the destructor

I have the following program:

#define _CRTDBG_MAP_ALLOC

#include <iostream>

using namespace std;

class test {
public:
    int* a;
    test() {
        a = new int[10];
    }
    ~test() {
        delete[] this->a;
    }
};

int main()
{
    test t;
    _CrtDumpMemoryLeaks();
    return 0;
}

And I get memory leaks, even though I free the memory in the destructor, I get memory leaks:

Detected memory leaks!
Dumping objects ->
{76} normal block at 0x011B95F0, 40 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
Object dump complete.

But if I change the code to this:

class test {
public:
    int* a;
    test() {
        a = new int[10];
    }
    ~test() {
        //delete[] this->a; commented this
    }
};

int main()
{
    test t;
    delete[] t.a; // added this
    _CrtDumpMemoryLeaks();
    return 0;
}

I don't get any memory leaks.

Why does this happen? How to fix it? I want to free the memory in the destructor.

Upvotes: 0

Views: 101

Answers (1)

Faker
Faker

Reputation: 131

The lifetime of a is different in the two programs.

#define _CRTDBG_MAP_ALLOC

#include <iostream>

using namespace std;

class test {
public:
    int* a;
    test() {
        a = new int[10];
    }
    ~test() {
        delete[] this->a;
    }
};

int main()
{
    test t;
    _CrtDumpMemoryLeaks();
    return 0;
} // <----- a die here. -----------------------
class test {
public:
    int* a;
    test() {
        a = new int[10];
    }
    ~test() {
        //delete[] this->a; commented this
    }
};

int main()
{
    test t;
    delete[] t.a; // <----- a die here. -----------------------
    _CrtDumpMemoryLeaks();
    return 0;
}

Upvotes: 6

Related Questions