-1
void LinkedList :: reverseL(int val)
{
    if (val==0 || head==NULL)
    {
        return;
    }
    else
    {
    Node *temp=NULL;
    Node *curr=head;
    Node *bef=NULL;
    Node *aft=curr->next;
    for (int j=0; j<length()-val; j++)
    {
        temp=curr;
        curr=aft;
        aft=aft->next;
    }
    int i=0;
    while (curr!=NULL && i<val)
    {
        curr->next=bef;
        bef=curr;
        curr=aft;
        if (aft==NULL)
        {
            break;
        }
        if (aft!=NULL)
        {
            aft=aft->next;
        }
        i++;
    }
    temp->next=bef;
    }
}

I am just trying to figure out why I am getting a core segmentation fault for any val>=the length of the linkedlist. Can anyone point me in the right direction?

GDB shows Seg fault at temp->next=bef; Not sure how to fix that...

Was
  • 9
  • 2
  • 2
    A debugger will figure out the reason for you, have you tried using it? – Quimby Oct 07 '22 at 18:39
  • 2
    I second the suggestion that you [step through your code in a debugger](https://stackoverflow.com/questions/25385173). Being able to use a debugger is a vital skill for all programmers. – Drew Dormann Oct 07 '22 at 18:43
  • 1
    Please try to learn debugging using a debugger. Debugging is a technique that not only helps you identify and address bugs, it is also an important skill to have for any programmer. Run your program using a debugger. Use gdb if that is accessible to you. It is time consuming for anyone here to go by a program where there are lots of pointer manipulation happening and one have to keep track of what was modified previously. – void Oct 07 '22 at 18:48
  • Thank you all for the suggestions I will use GDB to attempt to pinpoint the pointer error. – Was Oct 07 '22 at 19:18
  • I usd GDB and the seg fault is from temp->next=bef; Not sure how to go about fixing it. The function is meant to reverse the last k values of a linked list. – Was Oct 07 '22 at 20:20
  • *"GDB shows Seg fault at temp->next=bef;"* -- next step: at this point in execution, what are the values involved in this statement (`temp`, `temp->next`, and `bef`)? – JaMiT Oct 08 '22 at 00:37

1 Answers1

1

As you have found while debugging, the invalid dereferencing happens at temp->next=bef.

This error will happen when you call the reverseL method with a val that is equal the list's length. In that case temp will remain NULL, and thus temp->next is an invalid access. In this case you don't want to assign bef to temp->next, but to head.

So in your code replace:

temp->next=bef;

with:

if (temp == nullptr) {
    head = bef;
} else {
    temp->next = bef;
}

On a final note, in C++ you should be using nullptr instead of NULL.

trincot
  • 317,000
  • 35
  • 244
  • 286