Listing source code with list
What you'll learn: How to view your C source code from within the GDB debugger to keep track of where you are.
When you are debugging a program, it is easy to feel like you are flying blind. Since GDB is a text-based tool, you don't have a visual cursor blinking on a screen to show you which line of code is currently executing. The list command (or just l) is your flashlight—it lets you peer into your source file without leaving the debugger.
Using the list command
Once you have started GDB with your compiled program, simply type list and press Enter. By default, GDB will show you ten lines of code centered around the current point of execution. If you haven't started running the program yet, it usually starts from the beginning of your main function.
Think of it like looking through a small window at a long scroll. If you type list again immediately after, GDB will show you the next ten lines. You can keep doing this to scroll through your entire file.
Targeting specific areas
You don't always want to start at the beginning. You can tell GDB exactly where to point its flashlight by providing arguments:
list 20: Shows the code surrounding line 20.list main: Shows the code at the start of themainfunction.list 15, 25: Shows the specific range from line 15 to line 25.
Why this matters
Imagine you are investigating a crash. You’ve set a breakpoint, and the program has stopped. Without list, you are looking at a blank prompt. By listing the code, you can see the variables and logic surrounding the current line, helping you decide which variable to print or which function to step into next.
#include <stdio.h>
int main() {
int x = 10;
int y = 0;
// If your program crashes here,
// 'list' helps you see the division logic.
int result = x / y;
printf("Result: %d\n", result);
return 0;
}
If you compiled this with the -g flag (which is required for GDB to "see" your text), typing list inside GDB would show you exactly these lines, complete with their line numbers.
Key takeaway
Use the list command (or l) to display your source code and orient yourself during a debugging session.