Home > Net >  c pushing pointer onto pointer priority queue causes immediate valgrind errors
c pushing pointer onto pointer priority queue causes immediate valgrind errors

Time:10-22

I'm working on a Huffman code implementation in c , however during the construction pushing a pointer onto a priority queue of class pointers is causing several of the type of valgrind error shown below:

==1158==    at 0x40508E: void std::__push_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, Node*, nodeCompare>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, long, Node*, nodeCompare) (stl_heap.h:182)
==1158==    by 0x4034B5: void std::push_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, nodeCompare>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, __gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, nodeCompare) (stl_heap.h:221)
==1158==    by 0x4027AB: std::priority_queue<Node*, std::vector<Node*, std::allocator<Node*> >, nodeCompare>::push(Node* const&) (stl_queue.h:499)
==1158==    by 0x40177A: HuffmanCode::HuffmanCode(std::map<char, int, std::less<char>, std::allocator<std::pair<char const, int> > >) (huffmanCodes.cpp:117)
==1158==    by 0x401F78: main (huffmanCodes.cpp:188)
==1158==  Uninitialised value was created by a stack allocation
==1158==    at 0x404EF3: void std::__push_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, Node*, nodeCompare>(__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocator<Node*> > >, long, long, Node*, nodeCompare) (stl_heap.h:178)

Here's the code that I believe to be relevant to the issue:

struct nodeCompare{
  bool operator()(Node const& n1, Node const& n2){
    return n1.getFreq() > n2.getFreq();
  }
};

// huffman code constructor, takes in character frequency map
HuffmanCode::HuffmanCode(map<char, int> m){
  // creates priority_queue, creates leafs and adds them to the queue
  priority_queue<Node*, vector<Node*>, nodeCompare> PQ;
  for(auto item: m){
    Node* temp = new Node(item.first, item.second, true);
    PQ.push(temp); // causes error
  }

  // builds rest of tree upward until there is only a single element left (the root)
  while(PQ.size() > 1){
    Node* temp = new Node(false);
    Node* left = PQ.top(); // causes error
    PQ.pop();
    Node* right = PQ.top();
    PQ.pop();

    temp->setLChild(left);
    temp->setRChild(right);
    temp->setFreq(left->getFreq()   right->getFreq());
    PQ.push(temp); // causes error
  }

There's more code below this in the project, but I think this is what's causing the issue. Any help/insight would be appreciated.

CodePudding user response:

shoud use pointer in nodeCompare

struct nodeCompare{
  bool operator()(Node* n1, Node* n2){
    return n1->getFreq() > n2->getFreq();
  }
};
  • Related