Lesson 37 / 38

Debugging Basics

Find bugs with printf, compiler warnings and gdb breakpoints and stepping.

printf debugging

The simplest technique: sprinkle printf calls to print variable values and confirm which lines actually run. Fast, but requires editing and recompiling each time.

Compile with debug symbols

-g embeds debug info gdb needs; -Wall -Wextra surfaces suspicious code before you even run it.

gcc -g -Wall -Wextra prog.c -o prog
gdb ./prog

A minimal gdb session

Inside gdb: break main sets a breakpoint, run starts the program, next steps line by line, and print x inspects a variable's current value.

Final quiz 1 of 8

Final quiz

Quick check: What does gcc hello.c -o hello do?

  • Runs the program
  • Deletes hello.c
  • Compiles the source into an executable
  • Installs gcc
Answer

Compiles the source into an executable — -o names the output file.

Final quiz 2 of 8

Final quiz

Quick check: What is 7 / 2 in C with ints?

  • 3.5
  • 4
  • 2
  • 3
Answer

3 — Integer division truncates.

Final quiz 3 of 8

Final quiz

Quick check: Why use fgets instead of scanf("%s")?

  • It limits input to the buffer size
  • It is shorter
  • It parses numbers
  • It ignores spaces
Answer

It limits input to the buffer size — scanf %s has no bounds checking.

Final quiz 4 of 8

Final quiz

Quick check: What does *p do when p is a pointer?

  • Gets its address
  • Accesses the value it points to
  • Frees it
  • Declares it
Answer

Accesses the value it points to — * dereferences a pointer.

Final quiz 5 of 8

Final quiz

Quick check: Why does swap(int x, int y) fail to swap the caller's variables?

  • C forbids swapping
  • The compiler removes it
  • Arguments are copied
  • It needs a header
Answer

Arguments are copied — Pass pointers to modify the originals.

Final quiz 6 of 8

Final quiz

Quick check: Which function allocates memory on the heap?

  • printf
  • strlen
  • fopen
  • malloc
Answer

malloc — Pair every malloc with one free.

Final quiz 7 of 8

Final quiz

Quick check: What should you do with a pointer right after free()?

  • Set it to NULL
  • Free it again
  • Use it
  • Cast it to int
Answer

Set it to NULL — It avoids dangling-pointer use.

Final quiz 8 of 8

Final quiz

Quick check: Which tool can detect buffer overflows at runtime?

  • make clean
  • AddressSanitizer
  • ls
  • diff
Answer

AddressSanitizer — Compile with -fsanitize=address.