GDB为什么显示不正确的向量大小?

时间:2019-07-09 18:42:45

标签: c++ vector gdb

我一直在尝试调试使用多个STL向量的程序,似乎GDB(7.6.1)错误地显示了向量的大小(即元素数量,而不是容量)。不用说,这给调试我的代码造成了很大的困难。我创建了一个简单的代码来复制问题,vector_test.cpp。运行Windows 64位。

#include <vector>
#include <iostream>

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

    v.push_back(4);
    std::cout << "v.size() = "<<v.size()<<"\n";
    v.push_back(8);
    std::cout << "v.size() = "<<v.size()<<"\n";
    v.push_back(15);
    std::cout << "v.size() = "<<v.size()<<"\n";
    v.push_back(16);
    std::cout << "v.size() = "<<v.size()<<"\n";
    v.push_back(23);
    std::cout << "v.size() = "<<v.size()<<"\n";
    v.push_back(42);
    std::cout << "v.size() = "<<v.size()<<"\n";

    return 0;
}

使用g++ -Wall -g -O0 -o vector_test.exe vector_test.cpp编译并运行vector_test.exe之后,输出自然是

v.size() = 1
v.size() = 2
v.size() = 3
v.size() = 4
v.size() = 5
v.size() = 6

但是在GDB中进行调试却讲述了一个截然不同的故事……v.size()似乎被完全错误地评估了!

(gdb) break vector_test.cpp:5
Breakpoint 1 at 0x401477: file vector_test.cpp, line 5.
(gdb) run
Starting program: C:\Users\Robin Armstrong\Desktop/vector_test.exe
[New Thread 3384.0x1b64]
[New Thread 3384.0x2fa0]
[New Thread 3384.0x300c]
[New Thread 3384.0x1b10]

Breakpoint 1, main () at vector_test.cpp:5
5           std::vector<int> v;
(gdb) disp v.size()
1: v.size() = 1956771
(gdb) next
7           v.push_back(4);
1: v.size() = 0
(gdb)
8           std::cout << "v.size() = "<<v.size()<<"\n";
1: v.size() = 1
(gdb)
v.size() = 1
9           v.push_back(8);
1: v.size() = 3825453421
(gdb)
10          std::cout << "v.size() = "<<v.size()<<"\n";
1: v.size() = 412859506
(gdb)
v.size() = 2
11          v.push_back(15);
1: v.size() = 3825453421
(gdb)
12          std::cout << "v.size() = "<<v.size()<<"\n";
1: v.size() = 412859506
(gdb)
v.size() = 3
13          v.push_back(16);
1: v.size() = 3825453421
(gdb)
14          std::cout << "v.size() = "<<v.size()<<"\n";
1: v.size() = 4
(gdb)
v.size() = 4
15          v.push_back(23);
1: v.size() = 3825453421
(gdb)
16          std::cout << "v.size() = "<<v.size()<<"\n";
1: v.size() = 412859506
(gdb)
v.size() = 5
17          v.push_back(42);
1: v.size() = 3825453421
(gdb)
18          std::cout << "v.size() = "<<v.size()<<"\n";
1: v.size() = 6
(gdb)
v.size() = 6
20          return 0;
1: v.size() = 3825453421

我对于如何解释这一点完全不知所措,并且在其他地方找不到类似问题的描述。有什么想法吗?

0 个答案:

没有答案