I'm confident my earlier post is the answer author_unknown should look at. I hope the subsequent discussion doesn't hide that.
Quote:
Originally Posted by dwhitney67
r->link = NULL;
|
That was my first thought as well when looking at the code. But on inspection I saw that was not required.
Maybe it is good practice to initialize such pointers immediately when allocated, even when that initialization is reliably over written by subsequent code. Certainly that practice would avoid a lot of beginner mistakes.
Personally, I hate adding wasted steps to code. I often leave out such initialization and usually put in a comment explaining why I'm sure it is safe to leave out a particular initialization.
It's always tempting to respond to an ugly beginner example (of what should be simple code) with a complete clean rewrite.
I don't think that is a good idea. (oops, I failed to resist this time).
I think it is better to explain the specific issues in the code given. In this case, I just explained the bug that caused the segment fault. I could explain why many other details in the code are bad practice. But for the question asked in this thread, I guessed it would be best to just explain the bug itself.
But, while we're on the subject of clean rewrites, one problem in the original and just as bad in your version is too many possible paths. For a problem this simple, you shouldn't need all the exception cases coded that way. They make it too hard to desk check the logic and see that all paths are valid.
It is better to write the main path with enough generality that it covers all cases. The key to that in the add function is a Node** that is always valid and becomes the place you put the pointer to the new node and whose successor becomes the successor to the new node.
Code:
void add(struct Node** head, int num)
{
struct Node* newNode = malloc(sizeof(struct Node));
newNode->data = num;
while ( *head && (*head)->data<=num )
{
head = &((*head)->link);
}
newNode->link = *head;
*head = newNode;
}
If you also care about performance (and don't trust the optimizer) you might prefer:
Code:
void add(struct Node** head, int num)
{
struct Node* newNode = malloc(sizeof(struct Node));
newNode->data = num;
struct Node* node;
while ( (node=*head)!=NULL && node->data<=num )
{
head = &(node->link);
}
newNode->link = node;
*head = newNode;
}