通过前面的学习, 大家应该很了解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/licens

本文介绍了如何使用gdb调试因尝试对空vector执行操作(如front方法)导致的程序崩溃。强调了在使用STL时进行合法性检查的重要性,程序员应当负责避免此类错误,而不是依赖STL自身的异常处理。同时提醒,在实际项目中,忽视对空容器的判断经常会导致core dump,代码质量不容忽视。
1775

被折叠的 条评论
为什么被折叠?



