-1

I am having a bit of trouble with my Huffman Decoding function I have created. I was just wondering if anyone knew why my program was producing an infinite loop. Below is my function and how I caled it. When counter hits 8, it should exit out of the function because there are no more bits to read. Here it is:

HuffmanNode *rodee = createTree(freqArray2, 256); //holds the huffman tree
HuffmanNode *temporaryNode; //temporary node for traversing
temporaryNode = rodee; //first the temporary node is equal to the root
while(cin.read((char*)&w, sizeof(w))
{
  traverseCode(temporaryNode, rodee, bits, count);
  count = 0; //reset the count back to 0 for the next time the function is called 
} //as I read in a byte of 8 bits (I converted the bytes to bits in another function not shown

void traverseCode(HuffmanNode *temp, HuffmanNode *root, unsigned char *bits, int counter)
{
    if(counter >= 7)
    {
      counter = 0;
      return; 
    }
    if(temp->getLeft() == NULL && temp->getRight() == NULL)
    {
      cout << temp->getLetter();
      temp = root; 


      traverseCode(temp, root, bits, counter);
    }
    if((int)bits[counter] == 0)
    {
      traverseCode(temp->getLeft(), root,  bits, counter++);
    }
    if((int)bits[counter] == 1)
    {
      traverseCode(temp->getRight(), root, bits, counter++);
    }
}

Might anyone know why my function is going into an infinite loop and how to fix this? Thanks!

user200081
  • 563
  • 2
  • 12
  • 24

1 Answers1

0

If you expect counter to be updated by the traverseCode() function, it needs to be a reference or a pointer. In your code it's just a local variable, discarded when the function exits.

So this does nothing, other than return:

if(counter >= 7)
{
  counter = 0;
  return; 
}

This next bit is also confusing. It will call the function with the original value of 'counter', which may well be the source of your infinite loop. If it did actually return, it would increment the local value of counter and then then fall through to the next if(), which is also possibly unintended.

if((int)bits[counter] == 0)
{
  traverseCode(temp->getLeft(), root,  bits, counter++);
}
if((int)bits[counter] == 1)
{
  traverseCode(temp->getRight(), root, bits, counter++);
}

So you probably need to be handling counter completely differently, as well as not having your if() statements fall through like that.

JasonD
  • 16,464
  • 2
  • 29
  • 44