01 / 20

Runtime Errors &
Segmentation Faults

Understanding why C++ programs crash at runtime, what causes segmentation faults, and how to diagnose them like a pro.

C++

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

Source Code Compiler Syntax Check Executable Runtime Memory + Logic Compile Error CRASH!

Common Runtime Error Types

Segfault
Accessing memory your program doesn't own: null pointers, bad array indices, freed memory.
Logic Error
Program runs but produces wrong output: off-by-one bugs, wrong formulas, flipped conditions.
Overflow
Integer or stack overflow: exceeding numeric limits or infinite recursion depth.

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).

Virtual Memory Stack Heap Code/Data Unmapped Your Pointer ptr ✕ SIGSEGV

Top Causes of Segfaults

1
Dereferencing a null pointer: Using a pointer that was never assigned a valid address.
2
Array out-of-bounds access: Reading or writing past the allocated size of an array.
3
Use-after-free: Accessing memory through a pointer after it has been deallocated with delete.
4
Stack overflow: Infinite or very deep recursion that exhausts the call stack.
5
Writing to read-only memory: Modifying a string literal or const data segment.

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

1
Read the error message: Note "Segmentation fault (core dumped)" and any line numbers.
2
Compile with debug flags: Use -g and -fsanitize=address to get detailed stack traces.
3
Check all pointers: Verify they are initialized before use and not null.
4
Check array indices: Ensure every index \( i \) satisfies \( 0 \leq i < n \), where \( n \) is the array size.
5
Test incrementally: Add print statements or use a debugger (gdb) to find the exact crashing line.

Example 1: Null Pointer Dereference

C++ Code
int* ptr = nullptr; // ptr points to address 0 (nothing) cout << *ptr; // CRASH: dereferencing null

Example 2: Array Out of Bounds

C++ Code
int arr[5] = {10, 20, 30, 40, 50}; // Valid indices: 0, 1, 2, 3, 4 cout << arr[10]; // UNDEFINED BEHAVIOR arr[-1] = 99; // Writes to random memory!
10 [0] 20 [1] 30 [2] 40 [3] 50 [4] ?? [10] DANGER

Example 3: Use After Free

C++ Code
int* p = new int(42); delete p; // Memory freed cout << *p; // DANGLING POINTER! // p still holds the old address, // but that memory is no longer yours.

Example 4: Stack Overflow

C++ Code
void infinite() { infinite(); // No base case! } int main() { infinite(); // Stack grows until crash }
main() infinite() #1 infinite() #2 infinite() #3 ... Stack Limit Growth Each call adds a new frame No base case = infinite frames

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).

Sometimes works
Out-of-bounds reads may return stale data without crashing, making bugs hard to reproduce.
Sometimes crashes
The same code may crash on a different compiler, OS, or even different runs on the same machine.
Always dangerous
UB can corrupt memory silently, causing bugs far from the original mistake. Never rely on UB "working."

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

✕ Ignoring compiler warnings
Warnings about uninitialized variables or implicit conversions often lead to runtime crashes. Always compile with -Wall -Wextra.
✕ Assuming "it works = it's correct"
Undefined behavior may appear to work today but crash tomorrow. Passing tests does not prove absence of UB.
✕ Confusing segfault with compile error
Students often say "my code won't compile" when it actually compiles but crashes. These require different debugging strategies.

Question 1 of 5

Which of the following errors is detected during program execution, not at compile time?

Question 2 of 5

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++?