我正试图为我的BST编写析构函数,以便我不必手动删除所有内容。我已经尝试了多个析构函数为我的BST,但我一直得到内存泄漏时运行valgrind。下面是我的代码(析构函数位于代码末尾)。
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
//struct for names
struct User
{
string firstname;
string lastname;
};
//BST struct where the data in the BST are the names in struct User
struct BST
{
User* value;
int key=0;
BST* leftTree;
BST* rightTree;
};
// creates a BST ( I do it like this incase i want to run a new function on a BST, but with a field to keep track of the size and initialize to 0)
BST* createBST(){
BST* n = nullptr;
return n;
}
// checks if empty
bool isEmpty(BST* tree){
if(tree == nullptr){
return true;
}
return false;
}
// destroy the BST completely.
void destroy(BST* tree){
if (tree != nullptr){
delete tree->value;
destroy(tree->leftTree);
destroy(tree->rightTree);
delete tree;
}
}
Main查看代码是否工作:
// TEST to see if code works correctly.
int main() {
BST* bst = createBST();
// I don't have an insert function yet so I do it manually
bst = new BST;
bst->key = 15;
bst->value = new User{"John","15"};
bst->leftTree = new BST;
bst->leftTree->key = 5;
bst->leftTree->value = new User{"John","15"};
destroy(bst);
return 0;
}
编辑:新增删除树->value;但是我仍然得到这个错误:
==34== Memcheck, a memory error detector
==34== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==34== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==34== Command: student/labo12
==34==
==34== Conditional jump or move depends on uninitialised value(s)
==34== at 0x400923: destroy(BST*) (in /task/student/labo12)
==34== by 0x400950: destroy(BST*) (in /task/student/labo12)
==34== by 0x400950: destroy(BST*) (in /task/student/labo12)
==34== by 0x400ABD: main (in /task/student/labo12)
==34==
==34== Conditional jump or move depends on uninitialised value(s)
==34== at 0x400923: destroy(BST*) (in /task/student/labo12)
==34== by 0x400960: destroy(BST*) (in /task/student/labo12)
==34== by 0x400950: destroy(BST*) (in /task/student/labo12)
==34== by 0x400ABD: main (in /task/student/labo12)
==34==
==34== Conditional jump or move depends on uninitialised value(s)
==34== at 0x400923: destroy(BST*) (in /task/student/labo12)
==34== by 0x400960: destroy(BST*) (in /task/student/labo12)
==34== by 0x400ABD: main (in /task/student/labo12)
==34==
==34==
==34== HEAP SUMMARY:
==34== in use at exit: 0 bytes in 0 blocks
==34== total heap usage: 8 allocs, 8 frees, 208 bytes allocated
==34==
==34== All heap blocks were freed -- no leaks are possible
==34==
==34== For counts of detected and suppressed errors, rerun with: -v
==34== Use --track-origins=yes to see where uninitialised values come from
==34== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)
计算代码中new
和delete
操作符的数量。它们应该匹配。但是如果你的代码只关心BST
对象,而不删除User
。
为什么不实现BST
的析构函数来正确删除所有字段呢?
好的,在删除User
之后,你有一个错误初始化字段的问题。BST
没有显式的构造函数,所以指向左、右和user的指针都是用垃圾初始化的。这就是valgrind现在给你的建议。