When using GDB for debugging, it is frequently necessary to map specific memory addresses to line numbers in the source code. This capability is particularly useful when analyzing program crashes, for example, when you obtain a stack trace, which typically provides only memory addresses rather than source code line information. Below, I will detail how to convert addresses to their corresponding source code lines within GDB.
Steps
- Start GDB: Ensure your program was compiled with debugging symbols. This usually requires adding the
-gflag during compilation. For instance, for a C or C++ program, the compilation command could be:
bashgcc -g myprogram.c -o myprogram
- Load the program into GDB:
bashgdb ./myprogram
- Use the
listcommand: In GDB, you can use thelistcommand to associate a specific address with a line in the source code. The syntax is:
gdblist *address
For example, to locate the line for address 0x4005d4:
gdblist *0x4005d4
Example
Assume we are debugging a simple program that crashes due to an error in a function. When the error occurs, the stack trace obtained from GDB appears as:
shellProgram received signal SIGSEGV, Segmentation fault. 0x00000000004005d4 in mystery_function () at example.c:8
Here, 0x00000000004005d4 represents the program counter address at the crash point. To find the corresponding source code line in GDB, proceed as follows:
- Launch GDB and load the program:
bashgdb ./myprogram
- Enter the command to locate the address:
gdblist *0x4005d4
GDB will output information similar to the following, showing the corresponding line in the source code:
shell8 int x = *nullptr; // The statement causing the crash
Conclusion
Using the list *address command effectively assists developers in mapping addresses back to specific lines in the source code, which is essential for debugging and understanding program behavior. This approach proves particularly valuable when handling complex programs or investigating unexpected crashes.