c++ - 關於_CrtDumpMemoryLeaks
ringa_lee
ringa_lee 2017-05-16 13:23:55
0
1
730

剛剛自己寫二元樹來測試下_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....代表的是什麼?

#
ringa_lee
ringa_lee

ringa_lee

全部回覆(1)
phpcn_u1582

_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);

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!