Runtime Errors &
Segmentation Faults
Understanding why C++ programs crash at runtime, what causes segmentation faults, and how to diagnose them like a pro.
What is a Runtime Error?
A runtime error occurs when your program compiles successfully but encounters a problem while it is running. The compiler cannot catch these errors because they depend on conditions that only exist during execution: user input, memory state, or system resources.
Two Phases: Compile vs Run
Common Runtime Error Types
What is a Segmentation Fault?
A segmentation fault (segfault) occurs when your program tries to read or write memory that the operating system has not allocated to it. The OS detects this illegal access and terminates the process with a signal (SIGSEGV).
Top Causes of Segfaults
Compile vs Runtime vs Logic
| Compile Error | Runtime Error | Logic Error | |
|---|---|---|---|
| When detected | Before running | During execution | After inspecting output |
| Program runs? | No | Starts, then crashes | Yes, fully |
| Example | Missing semicolon | Null pointer deref | Off-by-one in loop |
| Difficulty to find | Easy (compiler says) | Medium (crash trace) | Hard (wrong output) |
How to Diagnose a Segfault
Example 1: Null Pointer Dereference
Example 2: Array Out of Bounds
Example 3: Use After Free
Example 4: Stack Overflow
The Ghost: Undefined Behavior
In C++, certain operations have undefined behavior (UB). This means the C++ standard does not define what should happen. The program might crash, produce garbage output, appear to work correctly, or even format your hard drive (theoretically).
Unsafe vs Safe Patterns
| Unsafe Pattern | Safe Alternative | |
|---|---|---|
| Array access | arr[i] without bound check | arr.at(i) throws exception |
| Raw pointer | int* p = new int; | std::unique_ptr<int> |
| C strings | char buf[10]; strcpy(...); | std::string |
| Recursion | No base case | Always define a base case |
| After delete | Use dangling pointer | Set to nullptr |
Common Mistakes to Avoid
Question 1 of 5
Which of the following errors is detected during program execution, not at compile time?
Question 2 of 5
int arr[3] = {1, 2, 3};
for (int i = 0; i <= 3; i++) {
cout << arr[i];
}
What is the primary issue with this code?
Question 3 of 5
What signal does the operating system send to a process that attempts an illegal memory access?
Question 4 of 5
A program uses delete p; and then later accesses *p. This is an example of:
Question 5 of 5
Which of the following is the safest alternative to raw pointer management in modern C++?