0
                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.

4
  • 2
    I'm guessing tmpPtr->next_number is NULL or uninitialized. Commented Mar 12, 2013 at 23:23
  • 1
    When using the debugger, which line caused the problem? Commented Mar 12, 2013 at 23:25
  • @DavidBrown I am guessing it is not properly linked. Any suggestions on how to fix it? Commented Mar 12, 2013 at 23:27
  • @ThomasMatthews the break point was if(tmpPtr->number<tmpPtr->next_number->number) Commented Mar 12, 2013 at 23:27

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

8 Comments

you need to check if tmpPtr->next_number is not NULL before trying to access any of its elements.
btw. you also need to set tmpPtr to the next element within the loop or you will get a endless loop.
but isnt h pointing to the head of the list, i.e the first element? So how is it null in the first run?
h->next_number is NULL after the first run, since it points to the same memory as n and you set n->next_number = NULL
Sorry to be a pain, would you mind submitting the correct code?
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.