Reputation:
if(tmpPtr->number<tmpPtr->next_number->number)
{
int tmpV1=tmpPtr->next_number->number;
int tmpV2=tmpPtr->number;
tmpPtr->next_number->number=tmpV2;
tmpV2=tmpPtr->number=tmpV1;
}
This is what I have tried so far, this is supposed to be sorting the linked list as member are being added each time. But when the compiler crashes when I try to put in the second node. The break point is the if statement, if(tmpPtr->number<tmpPtr->next_number->number)
. I tried really hard to figure out what the problem was, but couldnt.
Upvotes: 0
Views: 200
Reputation: 7468
Your problem is that on the second run tmpPtr
points to your first element which has a next_number
value of NULL
. So as soon as you try to dereference it, it will basically reduce itself to a NULL
pointer which leads to a SIGSEGV
.
after the first run
n->number = input
n->next_number = NULL
h = n
t = n
counter2 = 1
so starting with the second input
n->number
n->next_number = NULL
tmpPtr = h // which is the previous n and therefor h->next_number = NULL
tmpPtr->next_number == NULL // this is your problem since you do not check if next_number is a valid pointer
UPDATE: if uploaded a (hackish) version of a solution at https://gist.github.com/sahne/c36e835e7c7dbb855076
Upvotes: 2
Reputation: 587
for the second add, h->next_number is NULL, so on the first iteration of the inner while loop, you dereference NULL (alias of h->next_number->number).
Edit
When you're inserting the 2nd item:
head == tail, so head->next == NULL.
you start the inner loop:
head->number == first inserted item.
head->next == NULL.
head->next->number == dereferenced NULL.
Upvotes: 1