How to Fix Null Pointer Dereference in Linked Lists
In this tutorial, you'll learn about How to Fix Null Pointer Dereference in Linked Lists. We cover key concepts, practical examples, and best practices.
Null pointer dereference in linked lists occurs when code follows a pointer that is NULL or nullptr, typically when traversing past the end of the list or accessing a node that has not been initialized.
Quick Fix
Wrong
struct Node {
int data;
Node* next;
};
void printList(Node* head) {
while (head != nullptr) {
std::cout << head->data << " ";
head = head->next;
}
}
int main() {
Node* list = nullptr;
// forgot to allocate
printList(list);
// This is actually OK because we check head != nullptr
// Worse: dereference without check
std::cout << list->data; // crash!
}
Segmentation fault (core dumped)
Right
void printList(Node* head) {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
}
Node* createNode(int data) {
Node* node = new Node;
node->data = data;
node->next = nullptr;
return node;
}
int main() {
Node* list = createNode(1);
list->next = createNode(2);
printList(list);
}
1 2
Fix for deleting nodes
void deleteNode(Node*& head, int value) {
if (head == nullptr) return;
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* current = head;
while (current->next != nullptr && current->next->data != value) {
current = current->next;
}
if (current->next != nullptr) {
Node* temp = current->next;
current->next = temp->next;
delete temp;
}
}
Prevention
- Always check for
nullptrbefore dereferencing any pointer. - Initialize pointers to
nullptrafter declaration. - Use
std::optionalorstd::unique_ptrto express ownership and nullability. - In Rust, the borrow checker prevents null dereferences entirely.
- Run with address sanitizer to catch null dereferences in tests.
DodaTech Tools
Doda Browser's memory debugger traces null pointer dereferences to their source. DodaZIP archives core dumps for post-mortem analysis. Durga Antivirus Pro detects null pointer exploits targeting linked structure traversal.
Common Mistakes with null pointer list
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world DS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro