share
Stack OverflowHow do I print the elements of a C++ vector in GDB?
[+250] [7] John Carter
[2008-10-31 10:33:14]
[ c++ debugging stl vector gdb ]
[ https://stackoverflow.com/questions/253099/how-do-i-print-the-elements-of-a-c-vector-in-gdb ]

I want to examine the contents of a std::vector in GDB, how do I do it? Let's say it's a std::vector<int> for the sake of simplicity.

(3) Similar question: stackoverflow.com/questions/427589/… (the link in the answer is very interesting). - Paolo Tedesco
(1) The new, better way to do this is in this question: stackoverflow.com/questions/2492020/… - dshepherd
[+310] [2008-10-31 10:33:23] John Carter

With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:

print *(myVector._M_impl._M_start)@myVector.size()

To print only the first N elements, do:

print *(myVector._M_impl._M_start)@N

Explanation

This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:

myVector._M_impl._M_start 

And the GDB command to print N elements of an array starting at pointer P is:

print P@N

Or, in a short form (for a standard .gdbinit):

p P@N

(4) Hehe, it's something that's bugged me before, so I just looked it up this morning and added it as a memo to myself (as Jeff himself recommended). - John Carter
(3) Also if you want just a particular vector element, myVector._M_impl._M_start + n (for the nth element) - mariner
(4) Not working for me. Cannot evaluate function -- may be inlined - wallyk
(3) To print a single element, e.g. the 2nd element: print (myVector._M_impl._M_start)[2] - jfritz42
(3) To find the special names (_M_impl etc) for your compiler under GDB 7.0+, use print /r myVector - Eponymous
(2) with GCC 5.2.0 (though I am sure it works for earlier versions), you can use print *(&myVector[0])@myVector.size(), which requires no specific knowledge of GCC stdlib internals. - bcumming
Thanks @Eponymous !! I was wondering how to arrive at the right inner member names. - agam
Not sure how much it helps in debugability, but in addition to this tip I also compiled with g++ -ggdb -O0 - daparic
Strangely for me myVector.size() doesn't work (or always returns 0). I can see the size only if I run -exec p myVector then it correctly displays the size and capacity in the returned pretty string. - MasterHD
1
[+92] [2010-01-23 13:23:51] Michał Oniszczuk [ACCEPTED]

To view vector std::vector myVector contents, just type in GDB:

(gdb) print myVector

This will produce an output similar to:

$1 = std::vector of length 3, capacity 4 = {10, 20, 30}

To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process of these is described on gdb wiki [1].

What is more, after installing above, this works well with Eclipse C++ debugger GUI (and any other IDE using GDB, as I think).

[1] https://sourceware.org/gdb/wiki/STLSupport

(22) This works fine as long as the vector elements are directly interpretable. But it doesn't help if the vector contains pointers to the items of interest. - wallyk
(1) I frankly don't find the gdb wiki page particularly readable, maybe because it's "slightly" outdated now? For instance, I had the impression that the suggested content of the $HOME/.gdbinit was necessary. At the moment I end up with no such file at all and gdb correctly showing the content of std::vector. However, since during my "rambling" attempts I just installed and then unistalled cgdb, and I already had libstdc++5 installed, I have no idea why the pretty printing did not work while now it works. - Enlico
Why is this the accepted answer? This does not work at all. - Philipp Ludwig
2
[+16] [2014-08-26 06:57:03] badeip

Put the following in ~/.gdbinit:

define print_vector
    if $argc == 2
        set $elem = $arg0.size()
        if $arg1 >= $arg0.size()
            printf "Error, %s.size() = %d, printing last element:\n", "$arg0", $arg0.size()
            set $elem = $arg1 -1
        end
        print *($arg0._M_impl._M_start + $elem)@1
    else
        print *($arg0._M_impl._M_start)@$arg0.size()
    end
end

document print_vector
Display vector contents
Usage: print_vector VECTOR_NAME INDEX
VECTOR_NAME is the name of the vector
INDEX is an optional argument specifying the element to display
end

After restarting gdb (or sourcing ~/.gdbinit), show the associated help like this:

gdb) help print_vector
Display vector contents
Usage: print_vector VECTOR_NAME INDEX
VECTOR_NAME is the name of the vector
INDEX is an optional argument specifying the element to display

Example usage:

(gdb) print_vector videoconfig_.entries 0
$32 = {{subChannelId = 177 '\261', sourceId = 0 '\000', hasH264PayloadInfo = false, bitrate = 0,     payloadType = 68 'D', maxFs = 0, maxMbps = 0, maxFps = 134, encoder = 0 '\000', temporalLayers = 0 '\000'}}

(2) thank you for the code! I guess there is a typo and "print *($arg0._M_impl._M_start + $elem)@1" should be "print *($arg0._M_impl._M_start + $arg1)@1"? I use the following modification: define print_vector if $argc == 2 if $arg1 >= $arg0.size()-1 printf "Error, %s.size() = %d, printing last element:\n", "$arg0", $arg0.size()-1 end print *($arg0._M_impl._M_start + $arg1)@1 else print *($arg0._M_impl._M_start)@$arg0.size() end end - user1541776
el magnifico! mochas gracias - daparic
3
[+14] [2009-03-01 14:53:31] Nikhil

'Watching' STL containers while debugging is somewhat of a problem. Here are 3 different solutions I have used in the past, none of them is perfect.

  1. Use GDB scripts from http://clith.com/gdb_stl_utils/ These scripts allow you to print the contents of almost all STL containers. The problem is that this does not work for nested containers like a stack of sets.

  2. Visual Studio 2005 has fantastic support for watching STL containers. This works for nested containers but this is for their implementation for STL only and does not work if you are putting a STL container in a Boost container.

  3. Write your own 'print' function (or method) for the specific item you want to print while debugging and use 'call' while in GDB to print the item. Note that if your print function is not being called anywhere in the code g++ will do dead code elimination and the 'print' function will not be found by GDB (you will get a message saying that the function is inlined). So compile with -fkeep-inline-functions


4
[+3] [2020-05-15 16:04:59] Mike P

I have been able to use:

p/x *(&vec[2])@4

to print 4 elements (as hex) from vec starting at vec[2].


5
[+2] [2024-07-04 16:08:06] Jiangpeng Li

This is an add-up to the answer by Michał Oniszczuk [1].

According to this [2] post in the issue, if you are using VSCode for development and your OS is Ubuntu 22.04, you can simply add the following code in your launch.json file.

"setupCommands": [
    {
        "description": "Test",
        "text": "python import sys;sys.path.insert(0, '/usr/share/gcc/python');from libstdcxx.v6.printers import register_libstdcxx_printers;register_libstdcxx_printers(None)",
        "ignoreFailures": false
    },
    {
        "description": "Enable pretty-printing for gdb",
        "text": "-enable-pretty-printing",
        "ignoreFailures": true
    }
]

This method simplified the answer mentioned in the gdb wiki [3] above, since you don't have to manually specify the Python module or put this script in the .gdbinit file. And I believe this also answers the question raised by @Enlico in his comment [4].

By the way, if you are using Python C++ debugger [5] in the VSCode like I do, you can use the following launch.json file out-of-the-box.

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python C++ Debug",
            "type": "pythoncpp",
            "request": "launch",
            "pythonConfig": "default",
            // "cppConfig": "default (gdb) Attach",
            "cppAttachName": "(gdb) Attach",
            "preLaunchTask": "Build"  // Specify your own build task here.
        },
        {
            "name": "(gdb) Attach",
            "type": "cppdbg",
            "request": "attach",
            "processId": "",
            "setupCommands": [
                {
                    "description": "Test",
                    "text": "python import sys;sys.path.insert(0, '/usr/share/gcc/python');from libstdcxx.v6.printers import register_libstdcxx_printers;register_libstdcxx_printers(None)",
                    "ignoreFailures": false
                },
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}

You might get a warning indicating "Missing Property 'Program'", but it seems everything works fine.

[1] https://stackoverflow.com/a/2123260/17301276
[2] https://github.com/Microsoft/vscode-cpptools/issues/1414#issuecomment-1370441279
[3] https://sourceware.org/gdb/wiki/STLSupport
[4] https://stackoverflow.com/questions/253099/how-do-i-print-the-elements-of-a-c-vector-in-gdb#comment105364944_2123260
[5] https://github.com/benibenj/vscode-pythonCpp

6
[0] [2024-03-21 08:54:57] liginity

The accepted answer ( Michał's [1]) should work with recent versions of gdb. But a "full-featured" gdb is required.

On Debian 12, two packages gdb (full-featured) and gdb-minimal provide command gdb, version 13:

  • gdb from package gdb could print content of std::vector.
  • gdb from package gdb-minimal could not directly print the content of std::vector.
[1] https://stackoverflow.com/a/2123260

7