c++ - About _CrtDumpMemoryLeaks

查看:106
本文介绍了c++ - About _CrtDumpMemoryLeaks的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

刚刚自己写二叉树来测试下_CrtDumpMemoryLeaks的用法, 代码如下, 我断点跟踪了发现所有节点都删除了啊, 但是 output 窗口还是有提示

#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;
}

这里我有两个问题想请教大家:

  1. 这份简单的代码哪里有内存泄漏

  2. 如何从_CrtDumpMemoryLeaks给出的提示信息得出自己内存泄漏之处, 需要那些基础知识? 再具体些, _CrtDumpMemoryLeaks给出的地址0x02EE2880等如何从代码中迅速找到, 毕竟写多点的话肯定不能手动找啊. 以及 09 00 00 00 00....代表的是什么?

解决方案

_CrtDumpMemoryLeaks();的时候 t 还没有析构啊

int main()
{
    {
        tree t;
        t.build();
    }
    _CrtDumpMemoryLeaks();
    return 0;
}

改成这样

从提示信息的data来找,就是你说的09 00 00 00那一串,这就是泄露内存的内容

09 00 00 00| 00 00 00 00| 00 00 00 00

0-3字节是int,小端序;4-7和8-11分别是左右指针,和起来就是new Node(9);

这篇关于c++ - About _CrtDumpMemoryLeaks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆