Home > Article > Backend Development > How to Print the Contents of a C `std::vector` in GDB?
Debugging C code can often involve examining the contents of data structures. This becomes especially challenging when dealing with complex structures like C vectors. To address this, this article explores how to print the elements of a std::vector
First, identify the pointer to the internal array that stores the vector elements. In GCC 4.1.2, this pointer is accessible through the expression myVector._M_impl._M_start.
To print the entire vector, use the following GDB command:
print *(myVector._M_impl._M_start)@myVector.size()
This command prints the elements of the vector, starting at the address myVector._M_impl._M_start and continuing for myVector.size() elements.
To print only the first N elements of the vector, modify the command as follows:
print *(myVector._M_impl._M_start)@N
This command prints the first N elements of the vector.
Explanation:
These commands work because they take advantage of the way vectors are implemented in GCC 4.1.2. The internal array is stored at the _M_impl._M_start field of the vector, and GDB's print P@N command allows you to print N elements of an array starting at pointer P.
Shortcuts:
You can also create a shortcut in your GDB initialization file (.gdbinit) to simplify the debugging process. Add the following line to your .gdbinit file:
define p P@N
This creates an alias for the print P@N command, allowing you to use p to print array elements more conveniently.
The above is the detailed content of How to Print the Contents of a C `std::vector` in GDB?. For more information, please follow other related articles on the PHP Chinese website!