jamessxiao jamessxiao - 2 months ago 14
C++ Question

Trouble debugging Segmentation Error over a Linked List Function

Implementing a function that inserts a new node (key = newKey) after an existing node (with key = oldkey). If newKey isn't found in the node, then no action is performed.

This is my node constructor:

struct Node {
int key;
Node* next;
};


This is my method:

void insert_after(Node* head, int oldKey, int newKey){

Node* currNode = NULL;
Node* nextNode = NULL;
Node* newNode = NULL;

if (head == NULL) {
return;
}

currNode = head;
newNode->key = newKey;

while (currNode != NULL) {

if (currNode->key == oldKey) {

// oldKey is anywhere but last node

if (currNode->next != NULL) {
nextNode = currNode->next;
newNode->next = nextNode;
currNode->next = newNode;
break;
}

// oldKey is at the last node

else {
currNode->next = newNode;
newNode->next = NULL;
break;
}
}

currNode = currNode->next;
}

}


Thanks in advance!

Answer

You are trying to dereference a null pointer:

currNode = head;
newNode->key = newKey;  // <-- newNode is NULL

if (head == NULL) {

Also, this is C++; no need to declare all variables at the beginning of the scope. Declare and initialize variables as they are needed to help avoid this. For example, this is more obviously wrong:

Node* newNode = NULL;   // or "nullptr" if using C++11
newNode->key = newKey;