Just started with creating a Linked List in C. Getting runtime error in the code for returnLastNode. How do I know? Runs fine when it’s commented out.
Question#1 What am I doing wrong?
Code for my returnLastNode function
struct Node* returnLastNode(struct LinkedList *ll) {
struct Node *n = ll->first;
struct Node *result;
while(1) {
if(n->next == NULL) {
result = n;
break;
} else {
n = n->next;
}
}
return result;
}
Definition of structs used.
struct Node {
int val;
struct Node *next;
};
struct LinkedList {
struct Node *first;
};
LinkedList.h here, if needed/interested.
https://github.com/MoonStruckHorrors/LinkedListC/blob/master/LinkedList.h
Question #2 How a newbie should debug runtime errors?
Also, any other suggestions are appreciated. 🙂
You never check if
nisNULLbefore dereferencing it. This means your code will crash when used on an empty list. Also you can get rid of the variableresultand justreturn n;in theif (n->next == NULL)part. So a better version of your code might look like this:As for debugging runtime errors, you can use
printfto check what data is for simple things, and for more complex things you can use a debugger like gdb (or sometimes IDEs (such as Visual Studio) come with integrated debuggers).