我正在对树结构实现插入/搜索,但在释放内存时遇到了问题。当我在 return 语句之前的代码末尾包含“delete currentNode”时,我在运行后不久遇到此错误:
Error in `./a.out': double free or corruption
当我不包括删除 currentNode 时,我的程序输出搜索结果的时间比我在产生段错误之前“删除”的时间长。我想知道我需要在哪里释放 currentNode 的内存,这样我就不会耗尽内存。
这是代码:
bool myEntry::search(Node *root, char *target)
{
myEntry::Node *currentNode = new myEntry::Node;
currentNode = root;
while(*target != '\0')
{
if((*target-97)== -53) myEntry::index = 27;
else
{
myEntry::index = *target++ - 97;
}
if(!currentNode->forward[myEntry::index])
return false;
currentNode = currentNode->next[myEntry::index];
}
return (currentNode->correct);
}
最佳答案
您正在为新的 Node
分配内存对象,但永远不要使用它。相反,您会立即用指向 root
的指针覆盖指向新对象的指针。 .
当您调用 delete currentNode
,你不会删除你的新对象,但无论如何 currentNode
指向函数的末尾。
所以而不是myEntry::Node *currentNode = new myEntry::Node;
,只需写myEntry::Node *currentNode = root;
.
这样,您无需分配任何内存,因此您不必释放任何内存。
关于c++ - 在哪里释放内存而不引起错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59924491/