【发布时间】: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