C++ malloc:**对象错误:未分配要释放的指针***在malloc\u error\u break中设置断点以进行调试
有人能帮我找出这个错误是从哪里来的吗。我知道可能是双重删除或者类似的。作为背景,这是一个哈夫曼树的实现,您可以很容易地在上面实现C++ malloc:**对象错误:未分配要释放的指针***在malloc\u error\u break中设置断点以进行调试,c++,c,pointers,malloc,huffman-code,C++,C,Pointers,Malloc,Huffman Code,有人能帮我找出这个错误是从哪里来的吗。我知道可能是双重删除或者类似的。作为背景,这是一个哈夫曼树的实现,您可以很容易地在上面实现 intmain() { ifstream输入; input.open(“input.txt”); 最小优先级队列堆; 地图m; while(input.good()) m[input.get()]+=1; for(map::const_迭代器it=m.begin();it!=m.end();++it) enqueue(CharCountNode(it->first,
intmain()
{
ifstream输入;
input.open(“input.txt”);
最小优先级队列堆;
地图m;
while(input.good())
m[input.get()]+=1;
for(map::const_迭代器it=m.begin();it!=m.end();++it)
enqueue(CharCountNode(it->first,it->second));
while(heap.getSize()>1)
{
CharCountNode a、b、父节点;
a=heap.dequeue();
b=heap.dequeue();
parent=CharCountNode('*',a.getCount()+b.getCount());
parent.left=&a;
parent.right=&b;
heap.enqueue(父级);
}
}
此代码存在问题:
parent.left = &a;
parent.right = &b;
这是获取指向局部变量的指针,这些变量将在下次循环中重新初始化CharCountNode
最终将尝试删除这些对象,但new尚未分配它们
您需要使left
和right
指向堆上分配的对象,因为这是CharCountNode
所期望的。比如:
parent.left = new CharCountNode(a);
parent.right = new CharCountNode(b);
在malloc\u error\u break中设置断点以进行调试。应用valgrind
并修复它抱怨的第一件事。重复此操作,直到程序正常运行。截至本文发布时:valgrind不适用于Mac OS X 10.10。@cGetLegend使用虚拟机。
parent.left = new CharCountNode(a);
parent.right = new CharCountNode(b);