【问题标题】:C++ binary search tree template class memory leakC++二叉搜索树模板类内存泄漏
【发布时间】:2018-09-20 16:06:54
【问题描述】:

新手问题。我正在尝试编写二叉搜索树,但即使 一个简单的插入有内存泄漏。

文件节点.h

template<typename X> struct Node {
   X value;
   Node* left;
   Node* right;

   Node(X x) {
      this->value = x;
      this->left = nullptr;
      this->right = nullptr;
   }
};

文件 BST.h

template <typename X> class BST {
   public:
      BST() { root = nullptr; }

      bool Insert(const X& x) { return InsertAt(root, x); }

   private:

      bool InsertAt(Node<X>*& node, const X& x)
      {
         if (node == nullptr) {
            node = new Node<X>(x);
            return true;
         }

         if (node->value == x)
            return false;

         if (*(node->value) > *x)
            return InsertAt(node->left, x);

         return InsertAt(node->right, x);
      }

//----

      Node<X>* root;
};

主程序

#include "Node.h"
#include "BST.h"

int main(int argc, char **argv)
{
   BST<int*> bst;
   bst.Insert(new int(8));
}

g++ -g -fsanitize=address -fno-omit-frame-pointer -std=c++11 B.cpp 的输出 ==10646==错误:LeakSanitizer:检测到内存泄漏

Direct leak of 24 byte(s) in 1 object(s) allocated from:
    #0 0x7fb5e7f45532 in operator new(unsigned long) (/usr/lib/x86_64-linux-gnu/libasan.so.2+0x99532)
    #1 0x400eb7 in BST<int*>::InsertAt(Node<int*>*&, int* const&) /home/gc/BST.h:12
    #2 0x400e68 in BST<int*>::Insert(int* const&) /home/gc/BST.h:5
    #3 0x400d09 in main /home/gc/B.cpp:22
    #4 0x7fb5e778082f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)

Indirect leak of 4 byte(s) in 1 object(s) allocated from:
    #0 0x7fb5e7f45532 in operator new(unsigned long) (/usr/lib/x86_64-linux-gnu/libasan.so.2+0x99532)
    #1 0x400caf in main /home/gc/B.cpp:22
    #2 0x7fb5e778082f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)

SUMMARY: AddressSanitizer: 28 byte(s) leaked in 2 allocation(s).

首先,为什么会出现内存泄漏?二、为什么我会收到消息 当我的程序没有任何 unsigned long 时,关于 new(unsigned long)? 谢谢。

你可能会告诉我使用智能指针,但现在我只是想 教育自己关于指针的知识,并试图弄清楚为什么这不起作用。

【问题讨论】:

  • 你不会接受我的回答吗? :(

标签: c++11 memory-leaks binary-search-tree


【解决方案1】:

如果您不打算使用智能指针,那么您必须将每个newdelete 配对。由于您对new 的调用发生在每个类的构造函数中,因此您可以在析构函数中调用delete

无论如何,BST 中的析构函数应该是

~BST() { delete root; }

Node,它是

~Node() { delete left; delete right; }

这将递归地沿着树向下工作。您的递归情况是指向节点的指针不为空。与 free 在 null 上崩溃不同,delete 根本不做任何事情,使 nullptr 成为您的基本情况。

查看http://en.cppreference.com/w/cpp/language/destructor

【讨论】:

  • 是的,我必须告诉你只使用std::unique_ptr&lt;Node&lt;X&gt;&gt; 而不是担心newdelete。它节省了代码行数,使您的意图显而易见,然后就是整个“异常安全”问题。
  • 另外,我刚刚发现,既然在这种情况下,value是一个指针,我还需要~Node()中的delete value
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 2016-05-08
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
相关资源
最近更新 更多