Segmentation Fault in C++
A segmentation fault (segfault) occurs when a program tries to access a restricted or invalid memory location. This typically leads to a program crash.
Common Causes of Segmentation Faults in C++
1. Dereferencing a Null Pointer
Accessing memory through a nullptr
results in a segmentation
#include <iostream>
int main() {
int* ptr = nullptr; // Null pointer
std::cout << *ptr; // Dereferencing null (segfault)
return 0;
}
🔴 Fix: Always check if the pointer is nullptr
before dereferencing.
if (ptr != nullptr) {
std::cout << *ptr;
}
2. Accessing Memory Out of Array Bounds
If an array index goes beyond its allocated size, it accesses unallocated memory.
#include <iostream>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
std::cout << arr[10]; // Out-of-bounds access (segfault)
return 0;
}
🔴 Fix: Ensure index is within the valid range.
if (index >= 0 && index < 5) {
std::cout << arr[index];
}
3. Using an Uninitialized Pointer
A pointer that isn’t initialized points to a random memory address, leading to undefined behavior.
#include <iostream>
int main() {
int* ptr; // Uninitialized pointer
std::cout << *ptr; // Dereferencing garbage address (segfault)
return 0;
}
🔴 Fix: Initialize the pointer before use.
nt x = 10;
int* ptr = &x;
std::cout << *ptr;
4. Deleting Memory Twice (Double Free)
Freeing a pointer twice causes a segmentation fault.
#include <iostream>
int main() {
int* ptr = new int(5);
delete ptr;
delete ptr; // Double delete (segfault)
return 0;
}
🔴 Fix: Set pointer to nullptr
after deletion.
lete ptr;
ptr = nullptr;
5. Accessing a Deleted Pointer (Dangling Pointer)
Using a pointer after freeing its memory results in a segmentation fault.
ude <iostream>
int main() {
int* ptr = new int(10);
delete ptr;
std::cout << *ptr; // Accessing deleted memory (segfault)
return 0;
}
🔴 Fix: Avoid using pointers after deletion.
delete ptr;
ptr = nullptr; // Safe to check before access
6. Stack Overflow (Excessive Recursion)
Calling a function infinitely without a base case causes stack overflow.
recursiveFunction() {
recursiveFunction(); // Infinite recursion (stack overflow)
}
int main() {
recursiveFunction();
return 0;
}
🔴 Fix: Always include a base condition.
void recursiveFunction(int count) {
if (count == 0) return; // Base case
recursiveFunction(count - 1);
}
7. Using an Invalid Pointer from free()
or delete[]
Trying to access memory after calling free()
on a dynamically allocated block.
#include <iostream>
int main() {
int* arr = new int[5];
delete[] arr; // Memory is freed
std::cout << arr[0]; // Accessing freed memory (segfault)
return 0;
}
🔴 Fix: Set pointer to nullptr
after freeing.
delete[] arr;
arr = nullptr;
8. Buffer Overflow (Writing Beyond Allocated Memory)
Writing past an allocated memory boundary can corrupt adjacent memory.
#include <cstring>
int main() {
char str[5];
strcpy(str, "Hello, World!"); // Buffer overflow (segfault)
return 0;
}
🔴 Fix: Use strncpy()
or dynamically allocate sufficient memory.
char str[20];
strncpy(str, "Hello, World!", sizeof(str) - 1);
str[19] = '\0';
How to Debug a Segmentation Fault?
1. Using gdb
(GNU Debugger)
Compile with -g
flag:
g++ -g program.cpp -o program
Run the program with gdb
:
gdb ./program
Inside gdb
, run
If a segfault occurs, type:
backtrace
This shows the exact function and line number where the issue occurred.
Conclusion
✔ Always initialize pointers before use.
✔ Use bounds checking when accessing arrays.
✔ Avoid double freeing memory.
✔ Set pointers to nullptr
after deletion.
✔ Use debugging tools (gdb
, valgrind
) to find memory issues.
Leave a comment