I just wrote a binary tree to test the usage of _CrtDumpMemoryLeaks
. The code is as follows. I tracked the breakpoints and found that all the nodes have been deleted, but there is still a prompt in the output window
#include "stdafx.h"
#include <iostream>
#include <string>
#include <crtdbg.h>
class Node
{
public:
int data;
Node *lchild;
Node *rchild;
Node(int d) : data{ d }, lchild{ NULL }, rchild{ NULL } {}
};
class tree
{
public:
Node *root;
tree() : root{ NULL } {}
void build()
{
root = new Node(5);
root->lchild = new Node(6);
root->rchild = new Node(7);
root->lchild->lchild = new Node(8);
root->lchild->rchild = new Node(9);
in(root);
}
void remove(Node *node)
{
if (node->lchild != NULL)
{
remove(node->lchild);
}
if (node->rchild != NULL)
{
remove(node->rchild);
}
delete node;
}
void in(Node *node)
{
if (node->lchild != NULL)
{
preorder(node->lchild);
}
std::cout << node->data << " ";
if (node->rchild != NULL)
{
preorder(node->rchild);
}
}
~tree()
{
remove(root);
}
void convert(std::string &pre, std::string &in)
{
}
};
int main()
{
tree t;
t.build();
_CrtDumpMemoryLeaks();
return 0;
}
I have two questions to ask you here:
Where is the memory leak in this simple code
How to figure out the location of your own memory leak from the prompt information given by _CrtDumpMemoryLeaks
, what basic knowledge do you need? To be more specific, the address## given by _CrtDumpMemoryLeaks
How to quickly find #0x02EE2880 etc. from the code? After all, if you write more, you definitely can’t find it manually. And
09 00 00 00 00....What does stand for?
_CrtDumpMemoryLeaks(); when t has not been destroyed yet
Change it to this
Look from the data in the prompt message, it’s the string 09 00 00 00 you mentioned, this is the content of the leaked memory
Bytes 0-3 are int, little endian; 4-7 and 8-11 are left and right pointers respectively, and the sum is new Node(9);