# Lab 6: Debugging ## Tasks - Read and run the first example and observe the error. Then build in debug mode, and run the debugger to find the problem. - Read the second example, and come up with an assertion statement on `sum` that catches the bug. ## Description This lab aims to practice two debugging techniques: 1) Using a debugger 2) Adding assertion statements. Students also learn that they should enable debug symbols during the build process to make deubgger running possible. ## Debugging `example_1.c` Two problems: 1. Has a NULL pointer access for `prev` when inserting a value at the head of a non-empty list. 2. Does not insert values at the tail of a non-empty list. Steps to debugging: - Build program: `cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug` `cd build` `make` - Start debugger: `cgdb ./example1` - Run (`r`); will hit a test failure. Debug it: - Add breakpoint to main(): `b main` - Run: `r` - Step into: `s` - Step over: `n` - Step over again: just press ENTER - Walk through inserting the 1 (works), - Walk through inserting the 2; notice how **it finds the correct spot but does not insert**. - Add code to insert at tail (after the `while` loop): ```C // SOLUTION: Insert if it should go at end of list if (!inserted) { printf("Adding at the end! : %lu\n", data); prev->next = new_node; new_node->next = NULL; } ``` - Recompile, re-run debugger; Run: `r`, will crash. - Investigate value of `data` (`print data`) - Investigate list: `print head`, `print head.data` - Understand we are inserting at the head of the list. - Investigate state of algorithm: `print curr`, `print prev` - Add code to fix the bug (changing `prev-next = new_node`): ```C // SOLUTION: Handle value being inserted at head of list. if (prev == NULL) { head = new_node; } else { prev->next = new_node; } ``` ## Debugging `example_2.c` The provided code runs without any indication of a failure, but it has a function bug in insertion where the newly-inserted node is incorrectly connected to the one after the expected node, effectively causing an item to be dropped. This is supposed to be difficult to be identified by manually debugging, thus we suggest adding assertions. Again, as assertions for insertion operation is generally difficult, we suggest adding assertions over a side property, sum of the items. Sum is calculated in two ways so the unintended item drop is detected. Instructions and motivations behind each approach is expected to be discussed followed with a demonstration of using the tools (e.g., `cgdb`).