malloc: *** error for object: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug

余生长醉 提交于 2019-12-23 06:59:03

问题


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.

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);
  }
}

回答1:


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.

You need to make left and right point to objects allocated on the heap, as that is what CharCountNode is expecting. Something like:

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


来源:https://stackoverflow.com/questions/22824802/malloc-error-for-object-pointer-being-freed-was-not-allocated-set-a-br

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!