TL;DR
Your C program crashed with a segmentation fault (segfault). This guide shows you how to find the problem and fix it. We’ll use a debugger like GDB to step through your code, identify where the crash happens, and understand why.
1. Understand Segmentation Faults
A segfault means your program tried to access memory it shouldn’t. Common causes include:
- Dereferencing a null pointer: Trying to use a pointer that doesn’t point to valid memory.
- Accessing an array out of bounds: Reading or writing beyond the allocated size of an array.
- Stack overflow: Using too much memory on the stack (often due to deep recursion).
- Writing to read-only memory: Trying to modify a section of memory that’s protected.
2. Compile with Debugging Symbols
Make sure you compile your program with debugging symbols. This adds information that the debugger needs to understand your code.
gcc -g your_program.c -o your_program
3. Run Your Program Under GDB
Start GDB and load your program:
gdb your_program
4. Run the Program in GDB
Type run to start your program within GDB.
run
GDB will stop when it encounters a segfault and show you where the crash occurred.
5. Examine the Stack Trace (Backtrace)
Use backtrace or bt to see the call stack. This shows the sequence of function calls that led to the crash.
backtrace
The backtrace helps you understand which functions were involved and where the problem might originate.
6. Inspect Variables
Use print or p to examine the values of variables at the point of the crash. This is crucial for identifying null pointers, out-of-bounds array indices, or other incorrect values.
print variable_name
7. Step Through Your Code
Use these commands to control execution:
next(orn): Execute the next line of code, stepping over function calls.step(ors): Execute the next line of code, stepping *into* function calls.continue(orc): Continue execution until the next breakpoint or crash.
Step through your code line by line to see exactly what’s happening before the segfault.
8. Set Breakpoints
Set breakpoints at specific lines of code using break or b:
break filename:line_number
For example, to set a breakpoint on line 20 of your_program.c:
break your_program.c:20
9. Common Debugging Scenarios
- Null Pointer Dereference: Check if pointers are initialized before use and that they point to valid memory.
- Array Out of Bounds: Verify array indices are within the bounds of the array size. Use loops carefully, ensuring correct loop conditions.
- Stack Overflow: Reduce recursion depth or allocate larger stack space (though this is often a sign of poor algorithm design).
10. Example
Let’s say your program crashes with a segfault in a function called my_function. You might use:
backtraceto see the call stack.break my_functionto set a breakpoint at the beginning of the function.runto start execution and hit the breakpoint.nextorstepto step through the code, examining variables withprintas you go.