'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.
Solution 1:[1]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Remy Lebeau |
