通过前面的学习, 大家应该很了解gdb调试core了, 今天我们用gdb来调试对stl的空vector进行操作而产生的core.
先不说core, 而是来学学vector的front方法, 如下:
[taoge@localhost test]$ cat main.cpp
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
cout << v.front() << endl;
v.front() -= 10;
cout << v[0] << endl;
return 0;
}
[taoge@localhost test]$ g++ main.cpp
[taoge@localhost test]$ ./a.out
1
-9
[taoge@localhost test]$
要注意, v.front()是对vector首元素的引用, 所以可以做左值。 但是, 当vector为空的时候, 就有问题了, 产生了core, 如下:
[taoge@localhost test]$ cat main.cpp -n
1 #include <iostream>
2 #include <vector>
3
4 using namespace std;
5
6 int main()
7 {
8 vector<int> v;
9
10 cout << v.front() << endl;
11 v.front() -= 10;
12
13 cout << v[0] << endl;
14
15 return 0;
16 }
17
[taoge@localhost test]$ ls
main.cpp
[taoge@localhost test]$ g++ main.cpp
[taoge@localhost test]$ ls
a.out main.cpp
[taoge@localhost test]$ ./a.out
Segmentation fault (core dumped)
[taoge@localhost test]$ ls
a.out core.2917 main.cpp
[taoge@localhost test]$
[taoge@localhost test]$
[taoge@localhost test]$
[taoge@localhost test]$ gdb a.out core.2917
GNU gdb (GDB) Red Hat Enterprise Linux (7.1-29.el6)
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/g