
【Linux】栈保护 栈溢出 stack smashing detected 定位方法
栈保护 栈溢出 stack smashing detected 定位方法
- 一、Linux开发环境
- 二、关键词
- 三、背景
- 四、定位分析
- 1)第一种情况:变量的值被篡改。
- a)源代码(可不看)
- b)编译
- c)运行
- d)定位
- e)总结
- 2)第二种情况:程序报”stack smashing detected”然后终止。
- a)源代码(可不看)
- b)编译
- c)运行
- d)定位
- e)总结
一、Linux开发环境
OS:Ubuntu 16.04.1
编译工具:gcc 5.4.0
调试工具:gdb
二、关键词
栈保护
栈溢出
*** stack smashing detected ***
-fstack-protector
-fno-stack-protector
三、背景
gcc提供栈溢出保护机制,即默认编译时-fstack-protector选项为开。
在该保护机制下,如果程序中有栈溢出,会有以下报错信息,程序异常终止:
*** stack smashing detected ***: ./test terminated
Aborted (core dumped)若要关闭栈溢出保护,在gcc编译选项中增加-fno-stack-protector即可。
关闭后,如果程序中有栈溢出,仍可能会成功执行完,没有任何报错。
但实际上,栈溢出会导致程序中定义的变量被篡改。如果你的程序出现上面提到的两种异常:变量被篡改、或者栈溢出导致的异常终止,希望本文会对你有帮助。
四、定位分析
1)第一种情况:变量的值被篡改。
a)源代码(可不看)
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "math.h"
#include <ctype.h>int c2i(char ch)
{//如果是数字,则用ascii 减去48//isdight 判断数字函数if(isdigit(ch)){return ch-48;}//判断字母if(ch<'A'||(ch>'F'&&ch<'a')||ch>'z'){return -1;}//大写字母减去55,小写字母减去87if(isalpha(ch)){return isupper(ch)?ch-55:ch-87;}
}int hex2dec(char *hex)
{int len, num,temp,bits,i;num = 0;len = strlen(hex);//printf("len = %dn",len);for(i=0,temp=0;i<len;i++,temp=0){//printf("hex = %cn",hex[i]);//printf("num = %dn",num);temp = c2i(*(hex+i));//printf("temp = %dn",temp);bits = (len-i-1)*4;//printf("bits = %dn",bits);temp = temp << bits;//printf("temp = %dn",temp);num = num|temp;}return num;
}char* itoa(long int num,char *str,int radix)
{char index[] = "0123456789ABCDEF";long unsigned unum;int i=0,j,k;if(radix==10&&num<0){unum = (unsigned) -num;str[i++] = '-';}elseunum = (unsigned)num;do{str[i++] = index[unum%(unsigned)radix];unum/=radix;}while(unum);//printf("str = %sn",str);str[i] = '