Blog | G5 Cyber Security

C Seg Fault Debugging

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:

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:

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

10. Example

Let’s say your program crashes with a segfault in a function called my_function. You might use:

  1. backtrace to see the call stack.
  2. break my_function to set a breakpoint at the beginning of the function.
  3. run to start execution and hit the breakpoint.
  4. next or step to step through the code, examining variables with print as you go.
Exit mobile version