# Linked List Tutorial sample code question

• 01-16-2009
Kalleos
Linked List Tutorial sample code question
Hello everybody,

http://www.cprogramming.com/tutorial/c/lesson15.html

in the sample code of that Tutorial, which shows how one can traverse a linked list, there are some things I don't understand. Here is the part of the code. I've added a comment to the line I don't understand:

Code:

```/*...*/ struct node {   int x;   struct node *next; }; int main() {     /* This won't change, or we would lose the list in memory */     struct node *root;          /* This will point to each node as it traverses the list */     struct node *conductor;      root = malloc( sizeof(struct node) );      root->next = 0;  /* QUESTION: Why giving root->next a null pointer? */     root->x = 12;     conductor = root;     if ( conductor != 0 ) {         while ( conductor->next != 0)         {             conductor = conductor->next;         }     }     /*...*/ }```
Why is root->next set to a null pointer? Isn't root->next a null pointer by default?
Furthermore, there are 2 things I don't understand:

1. What is the use for "if ( conductor != 0 )" when they just wrote conductor = root before?

2. What is the goal of "while ( conductor->next != 0)"? If you just wrote "root->next = 0; conductor = root;" then is "conductor->next" in any case also 0! So the checking "while ( conductor->next != 0)" doesn't make any sense, because it's always 0.
• 01-16-2009
yougene
1.
if ( conductor != 0 )
is a roundabout way of checking if malloc was able to allocate memory to root. If no memory was allocated malloc returns a NULL pointer address.

2.
The code at hand is going to be part of a more complete linked list agorithm. The conditional will check if the loop has reached the end of a linked list. As it stands now, it doesn't do anything.
• 01-16-2009
matsp
Quote:

Originally Posted by yougene
1.
if ( conductor != 0 )
is a roundabout way of checking if malloc was able to allocate memory to root. If no memory was allocated malloc returns a NULL pointer address.

I agree with that - however the code is then broken, as it accesses root->next and root->x before checking that the pointer is non-null. Bad coding.

Edit: thinking about it, it probably makes more sense with Yougene's comment #2: This comes from a bigger project, and that check is essentially "Is the list completely empty".

--
Mats