Reputation: 754
I get what segfaults are and what causes them, my question is why is my pointer causing them? I'm trying to write a simple linked list that adds on nodes containing 5 and I get the segfault at temp->x = 5;. I thought malloc() should have allowed me access to the memory it needs?
#include <stdio.h>
#include <stdlib.h>
struct node{
int x;
struct node *next;
};
void append(struct node *root){
struct node *temp, *right;
temp = (struct node *)malloc(sizeof(struct node));
temp->x = 5;
right = (struct node *)root;
while(right->next != NULL){
right = right->next;
}
right->next = temp;
right = temp;
}
int main(){
struct node *root;
root = NULL;
int userInput;
printf("Pick Operation: ");
scanf("%d", &userInput);
if(userInput == 1){
append(root);
}
}
Upvotes: 0
Views: 87
Reputation: 51998
Insert the line
printf("%d is okay\n",temp->x);
right after temp->x = 5;
. Your program still crashes -- but only after it prints. Others have already pointed out the source of the error -- but it still doesn't hurt to know the basic trick of using judicious print statements to test your assumptions. Why did you think that line caused the error?
Upvotes: 1
Reputation: 2172
Your program does not cause a segfault at temp->x = 5;
.
It causes a segfault when you enter the while
loop. while(right->next != NULL)
Since you initialize your root
to null, so on the first call to append at the entrance of your while
loop, you check right->next
which is on a null object, and causes a segfault!!
Inserting an if
condition at the beginning would solve your purpose, something like this ::
if(root == NULL) {
root = temp;
} else {
while(right->next != NULL) {
/*your loop*/
}
}
Upvotes: 1
Reputation: 343
Your mistake is here:
while(right->next != NULL){
right = right->next;
}
You are trying to check "right->next" where "right" is NULL.
Upvotes: 1
Reputation: 14688
You are accessing a NULL pointer. The root is NULL
when you are calling append
, and in the code
...
right = (struct node *)root;
while(right->next != NULL){
...
then in you are trying to dereference the null pointer when you are accessing right-next
.
You need to step trough your code with a debugger.
Upvotes: 0