我有以下程序:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我遇到了内存泄漏,即使我在析构函数中释放了内存,我还是遇到了内存泄漏:
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.
Run Code Online (Sandbox Code Playgroud)
但如果我将代码更改为:
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;
}
Run Code Online (Sandbox Code Playgroud)
我没有遇到任何内存泄漏。
为什么会出现这种情况?如何修复它?我想在析构函数中释放内存。
两个程序中的生命周期a不同。
#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. -----------------------
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)