刚刚自己写二叉树来测试下_CrtDumpMemoryLeaks
的用法, 代码如下, 我断点跟踪了发现所有节点都删除了啊, 但是 output 窗口还是有提示
#include "stdafx.h" #include #include #include 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; }
这里我有两个问题想请教大家:
这份简单的代码哪里有内存泄漏
如何从_CrtDumpMemoryLeaks
给出的提示信息得出自己内存泄漏之处, 需要那些基础知识? 再具体些,_CrtDumpMemoryLeaks
给出的地址0x02EE2880
等如何从代码中迅速找到, 毕竟写多点的话肯定不能手动找啊. 以及09 00 00 00 00....
代表的是什么?
_CrtDumpMemoryLeaks();的时候 t 还没有析构啊
改成这样
从提示信息的data来找,就是你说的09 00 00 00那一串,这就是泄露内存的内容
0-3字节是int,小端序;4-7和8-11分别是左右指针,和起来就是new Node(9);