Debuggers and Memory Checkers
When a C program produces the wrong result or crashes, you need evidence about its execution. A debugger lets you pause a running program and inspect its state. A memory checker monitors execution for detectable memory errors. Debuggers and memory checkers answer complementary questions: what values led here, and what memory rules did this execution violate?
Pause execution and inspect state
GDB supports source-level inspection when the executable includes debugging information. For an initial investigation, use a build prepared with -g and usually -O0; optimization can make source lines and variables harder to follow. Keep the input that reproduces the failure.
Start with gdb ./reader, set a stopping location using break process, and begin execution with run samples.txt. GDB stops before executing the source line associated with the breakpoint. Use print count to inspect a value and info locals to inspect local variables in the selected function invocation.
Investigation goal | GDB command | What it does |
|---|---|---|
Inspect a called function | step | Enters a call when source information is available |
Advance within the current function | next | Executes calls without ordinary stepping stops inside them |
Resume ordinary execution | continue | Runs until another stopping event |
Find the active chain of calls | backtrace | Lists the current invocation followed by its callers |
Find where a value changes | watch count | Stops when the watched expression changes value |
Breakpoints and signals can interrupt stepping commands. A backtrace identifies the route to a failure; it does not establish that the currently executing function caused the original mistake. Use frame 1, for example, to select the caller and inspect its variables.
Read memory reports as evidence
Valgrind is a tool suite; Memcheck is its memory-checking tool. A useful invocation is:
valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all ./reader samples.txtAn invalid read or write reports an access to memory that Memcheck considers inaccessible. Read the access size, the location of the access, and any allocation or deallocation history. The access size is a number of bytes, not an array index.
For an allocated array containing N elements of size s bytes, the governing relationships are:
You may form a one-past pointer in C, but you may not dereference it to access an element. Similarly, freeing a block ends its allocated lifetime even if its old contents appear unchanged.
An undefined-value report concerns data that was not initialized before a consequential use, such as deciding a branch. It need not indicate an invalid address. Add --track-origins=yes to help locate where undefined data originated.
Interpret leaks and verify repairs
At a leak check, definitely lost blocks have no pointer chain that Memcheck can find. Indirectly lost blocks are accessible only through other lost blocks. Possibly lost blocks involve a pointer chain containing an interior pointer, which points inside a block rather than to its start. Still reachable blocks retain a recognized pointer chain; they are not automatically evidence of a lost allocation.
Fix the earliest relevant error, then rerun the reproducing input. Later reports may disappear when an earlier invalid write is repaired. Follow with boundary inputs and other execution paths: a clean run is evidence about the tested execution, not proof of complete correctness.
What to remember
- Use GDB to connect unexpected values to execution and callers.
- Separate address validity, initialization, and allocation lifetime.
- Interpret byte counts and leak categories before proposing a repair.
- Rerun the failing input and expand coverage after fixing the cause.
Example: Investigating a batch reader's boundary write
A sensor-data utility initializes a dynamically allocated batch using the function below. The required declarations are supplied elsewhere. Assume allocation succeeds, sizeof(int) is 4 bytes, and the executable contains source debugging information. An off-by-one error uses a boundary that permits one too many or one too few iterations.
void initialize_batch(void)
{
int *readings = malloc(6 * sizeof *readings);
if (readings == NULL) return;
for (int i = 0; i <= 6; ++i) {
readings[i] = i;
}
free(readings);
}Memcheck reports an invalid write of size 4 at readings[i] = i;, starting 0 bytes after the allocated block, when the program ./sensor_reader processes the input file samples.txt. In the source file batch.c, that assignment is on line 6.
a) Determine the allocation size and identify the first invalid array index.
The allocation contains ________. Its size is 24 bytes, calculated from the supplied element size:
The valid indices are ________. The loop nevertheless includes the iteration where i equals 6 because its condition uses <=.
The write's starting byte offset on that iteration is ________:
This equals the allocation size, so the write begins at the exclusive end boundary. The report's 0 bytes after the block means the access starts immediately beyond its valid storage; it does not mean the access is valid.
The allocation size is 24 bytes, and the first invalid index is 6.
b) Give GDB commands that stop before the invalid assignment, inspect the index, and identify the source repair.
Start GDB on the executable, set a conditional breakpoint on the assignment so that valid iterations do not interrupt the investigation, and run the program with the input that reproduced the Memcheck report:
gdb ./sensor_reader
break batch.c:6 if i == 6
run samples.txt
print iBecause samples.txt is the input that exercised this function under Memcheck, execution reaches the loop and GDB stops before the assignment on the failing iteration. The printed index is 6, which can be compared with the valid range from part a. A conditional breakpoint tests its condition each time execution reaches the specified location.
Inspect the index before executing the invalid write. Stepping beyond undefined behavior would not provide a reliable basis for predicting subsequent program results.
Repair the loop condition to exclude the one-past index:
for (int i = 0; i < 6; ++i) {
readings[i] = i;
}The final repair is i < 6, which initializes all six allocated elements without the extra write.
c) Describe a focused verification and the conclusion justified by a clean result.
Rebuild the executable after editing the source, then rerun the input that exercised this function under Memcheck:
valgrind --tool=memcheck --leak-check=full ./sensor_reader samples.txtCheck that the reported boundary write has disappeared. The function retains its free(readings) call, so the repaired successful path also releases its allocation after initialization.
Next test other relevant inputs and paths, such as an empty input and an input containing several batches. These tests extend the evidence beyond the original reproducer.
A clean result supports the repair on the execution tested. It does not establish that every input or every memory-error type has been checked.
A C program called parse crashes with a segmentation fault while reading records.txt. The executable you have was built without debugging information. You suspect the crashing function received a bad pointer from its caller, and you want to see the value that caller passed. Assume the caller's local pointer rec remains in scope and has not changed since the call. For this investigation, inspect the backtrace before selecting the caller's frame. Put these steps in the order you would carry them out.
Loading ordering steps…
A team investigating a Unix C application needs both execution inspection and memory-error detection. Match each tool or stopping mechanism to its defining purpose.
A stopping mechanism triggered when a monitored expression changes value
A tool that pauses execution so you can inspect program state
A stopping mechanism triggered when execution reaches a specified location
A runtime tool that detects supported violations involving storage access or use
Watchpoint
Breakpoint
Debugger
Memory checker