Explain and Diagnose a Segmentation Fault
Company: Hudson
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
# Explain and Diagnose a Segmentation Fault
Explain what a segmentation fault represents in a native program, how it relates to virtual-memory protection and C++ undefined behavior, and how you would diagnose one from a reproducible crash or core dump.
### Constraints & Assumptions
- Use POSIX `SIGSEGV` as the main example and note that other platforms use analogous mechanisms.
- Do not assume every invalid memory operation crashes immediately.
- Separate the faulting instruction from the earlier bug that corrupted state.
- Prefer diagnostic and prevention techniques over trying to continue after arbitrary memory corruption.
### Clarifying Questions to Ask
- Is the crash reproducible, intermittent, or dependent on optimized builds?
- Are symbols, a core dump, exact binaries, and source revision available?
- Can the workload be rerun with sanitizers or additional diagnostics?
- Is the process single-threaded, and did any earlier memory error appear in logs?
### Hints
- Inspect the signal, faulting address, instruction, registers, and every thread's stack.
- A null dereference is only one possible cause.
- Memory sanitizers often identify the earlier invalid access more directly than the final crash.
### What a Strong Answer Covers
- Page mapping and access protection, the operating-system signal or exception, and common causes.
- Undefined behavior that may corrupt data, appear to work, or crash later.
- Symbolized stack traces, core dumps, exact build artifacts, registers, disassembly, and memory mappings.
- AddressSanitizer, UndefinedBehaviorSanitizer, debuggers, watchpoints, minimization, and concurrency tools.
- Use-after-free, out-of-bounds access, stack overflow, bad function pointers, races, and protection violations.
- Root-cause correction, regression tests, ownership improvements, and why generic recovery is unsafe.
### Follow-up Questions
1. Why might an out-of-bounds write crash much later in an unrelated function?
2. How would a stack overflow appear in a debugger?
3. What evidence distinguishes use-after-free from an ordinary null dereference?
4. When can a signal handler safely do anything useful after `SIGSEGV`?
Quick Answer: Explain how a segmentation fault arises from protected virtual-memory access and why the faulting instruction may be far removed from the original C++ bug. Diagnose it with symbols, core dumps, registers, stack traces, sanitizers, debuggers, memory maps, and focused regression tests.