Dynamic Printf Debugging with GDB

When we debug a program with printf() we have to recompile it whenever we add new printf() statements! Right!?

Wrong!

With gdb we can add printf() statements without recompiling a program and even add them while it is running.

Adding Printfs with GDB

Let’s say we have the following example program that computes the sum of all the elements of an array:

#include <stdio.h>

int main(int argc, char **argv)
{
    int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int n = sizeof(numbers) / sizeof(numbers[0]);
    int sum = 0;

    for (int i = 0; i < n; i++) {
        sum += numbers[i];
    }

    printf("Sum of array: %d\n", sum);

    return 0;
}
Continue reading “Dynamic Printf Debugging with GDB”