Linux下和core说再见之:栈溢出

1. 概述
    栈,
就是那些由编译器在需要的时候分配,在不需要的时候自动清除的变量的存储区。里面的变量通常是局部变量、函数参数等;和堆相比,栈通常很小,在Linux下,通过ulimit -s可以查看栈的大小。

所谓栈溢出,是缓冲区溢出的一种,本质上是写入栈的数据超过栈的大小,使得数据写入其他单元,往往造成不可预期的后果,最常见的就是程序崩溃。

2. 实例
一个栈溢出的程序:

include <iostream>   using namespace std;      //递归函数    void stack_test(int group)   {       //占用栈内存,1M            char a[1024*1024];          //递归调用        group--;           if(group > 0)           {                   cout << "stack  " << group << endl;                   stack_test(group);           }      }      int main()   {       //函数层级            int layer;           cin >> layer;          //调用递归函数            stack_test(layer);              return 0;   }  

测试
linux 2.6.9xenu_5-0-0-0下输入命令:
$ ulimit -s
10240
表示栈内存限制10M

编译运行程序:
$ ./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  
[w@linuxidc 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)递归函数

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwgfzz.html