c – 简单代码导致错误读取变量:无法访问地址处的内存

我试图使用启用
python的gdb
MinGW-builds.我遇到了一个错误.这是一个相当简单的代码,它在MSVC下调试时工作正常.

D:\CppProject\c1\bin\Debug>gdb c1.exe
GNU gdb (GDB) 7.6
(copyright, license, bug report, etc omitted here)
Reading symbols from D:\CppProject\c1\bin\Debug\c1.exe...done.
(gdb) l
1       #include <iostream>
2       #include <vector>
3
4       using namespace std;
5
6       int main()
7       {
8           vector<string> v;
9           v.push_back("first");
10          v.push_back("second");
(gdb)
11          cout<<v[0]<<endl;
12          cout<<v[1]<<endl;
13
14          return 0;
15      }
(gdb) break 11
Breakpoint 1 at 0x4016c9: file D:\CppProject\c1\main.cpp, line 11.
(gdb) run
Starting program: D:\CppProject\c1\bin\Debug\c1.exe
[New Thread 1256.0xbe8]

Breakpoint 1, main () at D:\CppProject\c1\main.cpp:11
11          cout<<v[0]<<endl;
(gdb) p v
$1 = std::vector of length 2, capacity 2 = {"first", "second"}
(gdb) p v[0]
$2 = <error reading variable: Cannot access memory at address 0x29a2ca50>

最佳答案 这听起来很基本 – 你用-O0编译了吗?我怀疑编译器优化可能会给您带来麻烦.

点赞