如何在gdb中"观察"C++ std :: vector的大小?

end*_*gin 21 c++ gdb stdvector

我有一个std :: vector作为类的一部分,它包含一个自定义类型.它的内容似乎从程序的某个地方神秘地改变了.我无法弄清楚这是怎么回事.

有没有办法从gdb"观察"std :: vector的内容(或大小)?

谢谢.

Emp*_*ian 11

有没有办法从gdb"观察"std :: vector的内容(或大小)?

假设您正在使用GCC,请在theVector->_M_impl._M_start和上设置观察点_M_finish.如果您正在使用其他一些std :: vector实现,请相应地进行调整.

例:

#include <vector>

int main()
{
  std::vector<int> v;

  v.push_back(1);
  v.push_back(2);
}

g++ -g t.cc
gdb -q ./a.out

Reading symbols from /tmp/a.out...done.
(gdb) start
Temporary breakpoint 1 at 0x40090f: file t.cc, line 5.

Temporary breakpoint 1, main () at t.cc:5
5     std::vector<int> v;
(gdb) n
7     v.push_back(1);
(gdb) p v._M_impl._M_start
$1 = (int *) 0x0
(gdb) p v._M_impl._M_finish 
$2 = (int *) 0x0
(gdb) p &v._M_impl._M_finish
$3 = (int **) 0x7fffffffd878
(gdb) watch *$3
Hardware watchpoint 2: *$3
(gdb) p &v._M_impl._M_start
$4 = (int **) 0x7fffffffd870
(gdb) watch *$4
Hardware watchpoint 3: *$4
(gdb) c
Hardware watchpoint 3: *$4

Old value = (int *) 0x0
New value = (int *) 0x604010
std::vector<int, std::allocator<int> >::_M_insert_aux (this=0x7fffffffd870, __position=0x0) at /usr/include/c++/4.4/bits/vector.tcc:365
365       this->_M_impl._M_finish = __new_finish;
(gdb) bt
#0  std::vector<int, std::allocator<int> >::_M_insert_aux (this=0x7fffffffd870, __position=0x0) at /usr/include/c++/4.4/bits/vector.tcc:365
#1  0x0000000000400a98 in std::vector<int, std::allocator<int> >::push_back (this=0x7fffffffd870, __x=@0x7fffffffd88c) at /usr/include/c++/4.4/bits/stl_vector.h:741
#2  0x0000000000400935 in main () at t.cc:7
(gdb) c
Hardware watchpoint 2: *$3

Old value = (int *) 0x0
New value = (int *) 0x604014
std::vector<int, std::allocator<int> >::_M_insert_aux (this=0x7fffffffd870, __position=0x0) at /usr/include/c++/4.4/bits/vector.tcc:366
366       this->_M_impl._M_end_of_storage = __new_start + __len;
(gdb) bt
#0  std::vector<int, std::allocator<int> >::_M_insert_aux (this=0x7fffffffd870, __position=0x0) at /usr/include/c++/4.4/bits/vector.tcc:366
#1  0x0000000000400a98 in std::vector<int, std::allocator<int> >::push_back (this=0x7fffffffd870, __x=@0x7fffffffd88c) at /usr/include/c++/4.4/bits/stl_vector.h:741
#2  0x0000000000400935 in main () at t.cc:7

... etc...
Run Code Online (Sandbox Code Playgroud)

  • 由于我还是无法理解你的方法,你能详细解释一下你的方法吗?多谢。 (2认同)
  • *$1*、*$2*、... 是 gdb [值](https://ftp.gnu.org/old-gnu/Manuals/gdb/html_node/gdb_58.html#:~:text=Values)。它们可以用在表达式中。在本例中,您保留一个指向 _M_finish 变量的指针 *$3*,该变量指向最后一个值。然后你*观察*它所指向的值(\*$3),因此,当 _M_finish 更改(添加/删除新元素)时,你将到达观察点。 (2认同)