# Debugging Basics — C Programming Fundamentals: Pointers, Memory and Files

Source: https://www.skillbyai.com/en/c/c-debugging

> 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.

```bash
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

**Quiz:** What does gcc hello.c -o hello do?

- [ ] Runs the program
- [ ] Deletes hello.c
- [x] 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

**Quiz:** What is 7 / 2 in C with ints?

- [ ] 3.5
- [ ] 4
- [ ] 2
- [x] 3

*Answer:* 3. Integer division truncates.

## Final quiz 3 of 8

Final quiz

**Quiz:** Why use fgets instead of scanf("%s")?

- [x] 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

**Quiz:** What does *p do when p is a pointer?

- [ ] Gets its address
- [x] 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

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

- [ ] C forbids swapping
- [ ] The compiler removes it
- [x] Arguments are copied
- [ ] It needs a header

*Answer:* Arguments are copied. Pass pointers to modify the originals.

## Final quiz 6 of 8

Final quiz

**Quiz:** Which function allocates memory on the heap?

- [ ] printf
- [ ] strlen
- [ ] fopen
- [x] malloc

*Answer:* malloc. Pair every malloc with one free.

## Final quiz 7 of 8

Final quiz

**Quiz:** What should you do with a pointer right after free()?

- [x] 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

**Quiz:** Which tool can detect buffer overflows at runtime?

- [ ] make clean
- [x] AddressSanitizer
- [ ] ls
- [ ] diff

*Answer:* AddressSanitizer. Compile with -fsanitize=address.
