Linux ,c/c++, web,前端,php,js
分类: LINUX
2011-10-24 13:13:22
1. 概述
栈,就是那些由编译器在需要的时候分配,在不需要的时候自动清除的变量的存储区。里面的变量通常是局部变量、函数参数等;和堆相比,栈通常很小,在linux下,通过ulimit -s可以查看栈的大小。
所谓栈溢出,是缓冲区溢出的一种,本质上是写入栈的数据超过栈的大小,使得数据写入其他单元,往往造成不可预期的后果,最常见的就是程序崩溃。
2. 实例
一个栈溢出的程序:
编译运行程序:
$ ./bin/test
15
stack 14
stack 13
stack 12
stack 11
stack 10
stack 9
stack 8
stack 7
stack 6
stack 5
stack 4
Segmentation fault (core dumped)
core调试:
$ gdb /home/coresave/core.test.1
core.test.17380.1314809919 core.test.19889.1314811895
[work@bb-hm-test09.vm.baidu.com test]$ gdb ./bin/test /home/coresave/core.test.19889.1314811895
GNU gdb Red Hat Linux (6.3.0.0-1.96rh)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu"...Using host libthread_db library "/lib64/tls/libthread_db.so.1".
Core was generated by `./bin/test'.
Program terminated with signal 11, Segmentation fault.
Reading symbols from /usr/lib64/libstdc++.so.6...done.
Loaded symbols for /usr/lib64/libstdc++.so.6
Reading symbols from /lib64/tls/libm.so.6...done.
Loaded symbols for /lib64/tls/libm.so.6
Reading symbols from /lib64/libgcc_s.so.1...done.
Loaded symbols for /lib64/libgcc_s.so.1
Reading symbols from /lib64/tls/libc.so.6...done.
Loaded symbols for /lib64/tls/libc.so.6
Reading symbols from /lib64/ld-linux-x86-64.so.2...done.
Loaded symbols for /lib64/ld-linux-x86-64.so.2
#0 0x0000000000400abc in stack_test (group=3) at /home/work/zhouxm/test/src/main.cpp:18
18 cout << "stack " << group << endl;
3. 分析
原因:
1)栈中大数组char a[1024*1024];
2)递归函数
两个信息:
1)Program terminated with signal 11, Segmentation fault.
Signal 11, or officially know as "segmentation fault", means that theprogram accessed a memory location that was not assigned. That'susually a bug in the program.
2) core在 cout << "stack " << group << endl;
在栈溢出的时候,并不一定会马上core,这也是为啥你core的地方常常离出问题的代码很远。
4. 解决
1)在需要占用大内存的时候(例如,大数组),别偷懒,乖乖的用堆!
2)尽量避免层次多的递归函数
欢迎拍砖!补充!