(debugging)

CIS241

System-Level Programming and Utilities

C - Debugging

Erik Fredericks, frederer@gvsu.edu
Fall 2025

Based on material provided by Erin Carrier, Austin Ferguson, and Katherine Bowers

CIS241 | Fredericks | F25 | 39-c-debugging

Debugging

What is debugging?

  • Trying to fix a broken code

What is a debugger?

  • A program that lets you see what’s going on inside a program as it runs

Why use a debugger?

  • Helps fix segfaults and logic errors
  • Provides more insights than print statements
CIS241 | Fredericks | F25 | 39-c-debugging

Debugging

We’ll be using gdb (GNU Project Debugger)

Steps to run gdb:

  1. Compile your code in debug mode
  • gcc -g my_code.c
  1. Launch gdb with your executable
  • gdb ./a.out
CIS241 | Fredericks | F25 | 39-c-debugging

Mac users...

You will likely not have gdb

  • You can use lldb instead.

Use will be very similar, but some commands will have different names.

Reference: https://lldb.llvm.org/use/map.html

CIS241 | Fredericks | F25 | 39-c-debugging

Using gdb

(gdb)

.

Using gdb

You can run commands within gdb, basics include:

  • run - Start executing your program from the beginning
  • run arg1 arg2 for command line args
  • run < input_file > output_file (redirect)
  • quit - exit gdb
  • kill - stop program execution
CIS241 | Fredericks | F25 | 39-c-debugging

Debugging a segfault

♪~ ᕕ(ᐛ)ᕗ

  1. Start gdb to run program

  2. run

top-right (segfault gdb)

  1. Examine the callstack with backtrace or bt

  2. Load a frame (f) using its number (e.g., f 1)

CIS241 | Fredericks | F25 | 39-c-debugging

Debugging a segfault

  1. You can use list to get more context

  2. Check the state of your variables

  • Print a variable with print (or p) (e.g., p size)

  • Print n items of an array with *array@n

  1. Try to deduce the problem! You can always examine other frames
CIS241 | Fredericks | F25 | 39-c-debugging

Breakpoints

You can also use breakpoints to pause your code

To set a breakpoint:

  • break function_name
  • break line_number
  • break line_number if condition

To list all breakpoints: info break

CIS241 | Fredericks | F25 | 39-c-debugging

Breakpoints

continue will resume until next breakpoint

step to execute one line of code

  • step n to execute n lines of code

enable/disable breakpoint_number

delete breakpoint_number (delete for all)

CIS241 | Fredericks | F25 | 39-c-debugging

Other tools

Valgrind: "a suite of tools for debugging and profiling programs"

  • Valgrind is very powerful, but very complex.

Recommendation: memcheck

  • valgrind --tool=memcheck ./a.out

This will check for memory leaks and other hard-to-spot memory issues!

CIS241 | Fredericks | F25 | 39-c-debugging

point out the ./a.out and (gdb) interface

![bottom-corner (segfault gdb) w:500](img/segfault-gdb.png)

set breakpoint in function (break test) frame 0 frame 1

break 5 step step