1
void addToTree(SynTree *newNode){
    if(tree==NULL){
        tree=newNode;
        newNode->next=NULL;
    }else{
        SynTree *curr=tree;
        while(curr->next){
            curr=curr->next;
        }
        curr->next=newNode;
        newNode->next=NULL;
    }
}

incredibly basic c code that i've used in other places. It gets stuck in an infinite loop at the while statement. when I debug with gdb, it tells me that the 2nd node added to the tree is pointing to itself, thus causing the infinite loop. My question is, how? Maybe i'm too sleep deprived to be working right now, but I can't see what's wrong.

Chowlett
  • 45,935
  • 20
  • 116
  • 150

1 Answers1

0

In spite of that the function is written not very well there is no problem with adding a node to the list in the function.

It seems that the problem is that you are using a pointer to the same object (maybe a local object) when adding a new node to the list. You have to allocate dynamically each new node.

I can guess that your code looks something like

SynTree node;

while ( condition )
{
   // set internal data members of the node

   addToTree( &node );
   //..
}

Or

while ( condition )
{
    SynTree node;

   // set internal data members of the node

   addToTree( &node );
   //..
}

Instead of this incorrect approach you have to write like

while ( condition )
{
   SynTree *node = malloc( sizeof( SynTree ) );
   // set internal data members of the node

   addToTree( node );
   //..
}

that is each new node that is added to the list has to be allocated with using malloc or at least you have to pass to the function pointers to separate objects.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Would second one end with `curr->next == curr`? Would local `node` get the same address with every loop? Or is it just UB? – zoska Dec 02 '14 at 11:02
  • @zoska There is no guarantee that the local variable will have the same address. On the other hand there is no reason that this local varaibel will be reallocated in each iteration.:) – Vlad from Moscow Dec 02 '14 at 11:05