C++ malloc: *** 对象错误:未分配被释放的指针 *** 在 malloc_error_break 中设置断点以进行调试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22824802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
malloc: *** error for object: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug
提问by waldyr.ar
Can someone help me figure out where I'm getting this error. I know it's probably a double deletion or something like this. For the background this is an implementation of the huffman's tree as you can easily realize on wikipedia.
有人可以帮我弄清楚我在哪里收到此错误。我知道这可能是双重删除或类似的东西。对于背景,这是霍夫曼树的实现,您可以在wikipedia上轻松实现。
CharCountNode class implementation
int main()
{
ifstream input;
input.open("input.txt");
MinPriorityQueue<CharCountNode> heap;
map<char, int> m;
while(input.good())
m[input.get()] += 1;
for( map<char, int>::const_iterator it = m.begin(); it != m.end(); ++it )
heap.enqueue(CharCountNode(it->first, it->second));
while(heap.getSize() > 1)
{
CharCountNode a, b, parent;
a = heap.dequeue();
b = heap.dequeue();
parent = CharCountNode('*', a.getCount() + b.getCount());
parent.left = &a;
parent.right = &b;
heap.enqueue(parent);
}
}
采纳答案by The Dark
The problem is with this code:
问题在于这段代码:
parent.left = &a;
parent.right = &b;
This is getting pointers to local variables, which will be reinitialized next time around the loop. CharCountNode
will eventually try to delete
these objects, but they haven't been allocated by new.
这是获取指向局部变量的指针,下次循环时将重新初始化。CharCountNode
最终会尝试delete
这些对象,但它们还没有被 new 分配。
You need to make left
and right
point to objects allocated on the heap, as that is what CharCountNode
is expecting. Something like:
您需要创建left
并right
指向在堆上分配的对象,这正是我们CharCountNode
所期望的。就像是:
parent.left = new CharCountNode(a);
parent.right = new CharCountNode(b);