Title: I can't free the memory I declared in a class in the destructor
Tags: c++;class;memory-leaks
Question: I have the following program:
#define _CRTDBG_MAP_ALLOC
#include <iostream&gt;
using namespace std;
class test {
public:
int* a;
test() {
a = new int[10];
~test() {
delete[] this-&gt;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 -&gt;
{76} normal block at 0x011B95F0, 40 bytes long.
Data: <                &gt; 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-&gt;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.
Comment: `_CrtDumpMemoryLeaks();` cannot look into the future. It cannot distinguish between  a leak and something that has been allocated and will be deleted later

Comment: `test t;` ===> `{ test t; }` . Your object won't be destroyed (and as a function of that, the destructor fired) until it leaves current scope (which would mean, leaving `main`, which would mean you've already dumped what you think are memory leaks, but aren't (yet)). Alternatively, dynamically allocate and destroy the object before dumping. Or put the instance in the scope of a function called from `main`. Or a half dozen other things to ensure your object is allocated *and* destroyed before you dump leaks.

Comment: Note that `delete[] t.a;` introduces undefined behavior because `t`'s destructor deletes the same memory.


Here is another answer: The lifetime of a is different in the two programs.
#define _CRTDBG_MAP_ALLOC
#include <iostream&gt;
using namespace std;
class test {
public:
int* a;
test() {
a = new int[10];
~test() {
delete[] this-&gt;a;
int main()
test t;
_CrtDumpMemoryLeaks();
return 0;
} // <----- a die here. -----------------------
class test {
public:
int* a;
test() {
a = new int[10];
~test() {
//delete[] this-&gt;a; commented this
int main()
test t;
delete[] t.a; // <----- a die here. -----------------------
_CrtDumpMemoryLeaks();
return 0;

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2022:00:03/25/22', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c++><class><memory-leaks>', 'Title': "I can't free the memory I declared in a class in the destructor", 'ViewCount': 78, 'id': 71612474, 'user_AboutMe': None, 'user_AccountId': 21473857.0, 'user_DisplayName': 'vct12345', 'user_Reputation': 39.0, 'user_Views': 13.0, 'user_id': 15822443.0}}