The short answer
Most segmentation faults come from a small set of coding mistakes: a pointer that points nowhere useful, memory used after it has been released, an index past the end of an array, recursion that never stops, and writes to read-only memory. The examples below are deliberately broken, so compile them only to experiment.
Dereferencing a null or uninitialized pointer
A null pointer holds the value nullptr, which points to no object. Reading or writing through it is one of the most common causes of a crash:
int* count = nullptr;
*count = 5; // Writes through a null pointer
An uninitialized pointer is less predictable. If you declare int* p; and never assign it, the pointer holds whatever value was already in that memory, so it may point almost anywhere. Initializing every pointer when you declare it prevents this. Before using a pointer that might be null, check it:
if (count != nullptr) {
*count = 5;
}
If the idea of a null pointer is new to you, start with what is a null pointer in c.
Using memory after it has been freed
Once you call delete on a heap object, the allocator may reuse that memory. A pointer that still holds the old address is called a dangling pointer:
int* value = new int(10);
delete value;
std::cout << *value << '\n'; // value still holds the old address
Reading *value here is undefined behavior. The program might print a leftover number, print something random or crash. A safer habit is to set the pointer to nullptr after deleting it, or to avoid raw new and delete by using std::unique_ptr, which frees the object for you.
Indexing past the end of an array or vector
A C-style array of three integers has valid indexes 0, 1 and 2. Writing to index 10 goes well past the end:
int numbers[3] = {1, 2, 3};
numbers[10] = 99; // Outside the array; may corrupt other data or crash
A small overrun may go unnoticed, while a large one may land outside the program’s memory entirely. The same problem happens with std::vector when you use operator[], which doesn’t check the index:
std::vector<int> items = {1, 2, 3};
std::cout << items[5] << '\n'; // Undefined: operator[] does no bounds check
Calling items.at(5) instead throws a std::out_of_range exception, which you can catch and report. That turns a possible crash into an error you can see at the point where the bad index is used.
Runaway recursion
Each function call uses some stack space. A recursive function with no base case keeps calling itself until the stack runs out of room, and the operating system stops the program:
int countdown(int n) {
return countdown(n - 1); // Never stops
}
A base case fixes it:
int countdown(int n) {
if (n <= 0) {
return 0;
}
return countdown(n - 1);
}
A huge local array can exhaust the stack in the same way. With optimization turned on, a compiler may turn a simple recursive call into a loop, which can hang instead of crashing. That’s one more reason to debug with optimization off.
Writing into a string literal
const char* message = "hello";
char* writable = const_cast<char*>(message);
writable[0] = 'H'; // Undefined behavior; often a segfault
String literals are usually stored in read-only memory, so the write fails on many systems. The safe choice is char message[] = "hello";, which copies the text into a writable array, or a std::string.
Returning a pointer to a local variable
int* make_number() {
int local = 42;
return &local; // local is destroyed when the function returns
}
The returned pointer refers to memory that no longer belongs to the function. Using it is undefined behavior and often crashes. Most compilers warn about this pattern, so read those warnings rather than ignoring them.
A format string that doesn’t match
#include <cstdio>
int main() {
std::printf("%s\n", 42); // %s expects a char pointer, not an int
return 0;
}
printf trusts the format string, so %s reads the value 42 as an address. That address is almost certainly invalid. Compiling with -Wall usually produces a warning about the mismatch.
Dereferencing end()
#include <iostream>
#include <vector>
int main() {
std::vector<int> items = {1, 2, 3};
std::cout << *items.end() << '\n'; // end() is one past the last element
return 0;
}
end() returns an iterator one position past the last element, so dereferencing it is undefined behavior. Loops should stop when the iterator equals end() and never read through it.
Why these bugs can be hard to spot
All of these are undefined behavior. A program can run correctly in testing and then crash after a small change to the code, or on a different compiler. A clean run isn’t proof that the code is safe, so use warnings and sanitizers for more confidence.
Ways to reduce the risk
- Use
std::vector,std::stringandstd::array, and callat()while debugging. - Prefer
std::unique_ptrandstd::shared_ptrover rawnewanddelete. - Initialize every variable and pointer when you declare it.
- Compile with
-Wall -Wextraand treat warnings seriously. - Run tests with AddressSanitizer, or with Valgrind when a sanitizer isn’t available.
For the rules the operating system enforces when these mistakes happen, see what triggers segmentation fault.