malloc:***对象的错误:没有分配被释放的指针***在malloc_error_break中设置一个断点来调试

wal*_*.ar 14 c c++ malloc pointers huffman-code

有人可以帮我弄清楚我在哪里得到这个错误.我知道它可能是双重删除或类似的东西.对于背景,这是霍夫曼树的一个实现,你可以在维基百科上轻松实现.

CharCountNode类实现

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

The*_*ark 12

问题出在这个代码上:

parent.left = &a;
parent.right = &b;
Run Code Online (Sandbox Code Playgroud)

这是获取局部变量的指针,这些变量将在下次循环时重新初始化.CharCountNode最终将尝试delete这些对象,但它们尚未被新分配.

您需要创建leftright指向堆上分配的对象,因为这CharCountNode是期望的.就像是:

parent.left = new CharCountNode(a);
parent.right = new CharCountNode(b);
Run Code Online (Sandbox Code Playgroud)