gpt4 book ai didi

c++ - malloc: *** 对象错误:未分配被释放的指针 *** 在 malloc_error_break 中设置断点以进行调试

转载 作者:IT老高 更新时间:2023-10-28 22:39:28 25 4
gpt4 key购买 nike

谁能帮我弄清楚我在哪里得到了这个错误。我知道这可能是双重删除或类似的东西。作为背景,这是一个霍夫曼树的实现,您可以在 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);
}
}

最佳答案

问题在于这段代码:

parent.left = &a;
parent.right = &b;

这是获取局部变量的指针,下次循环时会重新初始化。 CharCountNode 最终会尝试 delete 这些对象,但它们还没有被 new 分配。

您需要使 leftright 指向在堆上分配的对象,这正是 CharCountNode 所期望的。比如:

parent.left = new CharCountNode(a);
parent.right = new CharCountNode(b);

关于c++ - malloc: *** 对象错误:未分配被释放的指针 *** 在 malloc_error_break 中设置断点以进行调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22824802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com