分配空间不足引起的错误:‘Stack smashing detected’

来源:互联网 发布:js object转字符串 编辑:程序博客网 时间:2024/04/20 01:11
 

分配空间不足引起的错误:‘Stack smashing detected’

分类: C++ linux 调试 4728人阅读 评论(0) 收藏 举报
querygccubuntuaccessbufferwindows

使用环境:ubuntu 11.10、C++

出错情景:

使用mysql执行一个query语句,以进行一个涉及多个表的联合查询(query语句比较长)

代码如下:

[cpp] view plaincopy
  1. char query[128]={0};  
  2. sprintf(query, ".....");  
  3. ...  
  4. return myList;  
执行结束之后,返回一个list类型的值

[cpp] view plaincopy
  1. #include <stdio.h>   
  2. void func()  
  3. {  
  4.     char array[10];  
  5.     gets(array);  
  6. }   
  7. int main(int argc, char **argv)  
  8. {  
  9.     func();  
  10. }  

-fno-stack-protector 

while compiling.
In that case you will get a segmentation fault if you try to access illegal memory location. and of course you can detect the point of overflow say for example using using valgrind.

但是,在执行完return语句时,弹出该错误:“** stack smashing detected ***:a.o terminated

寻找原因:

问题很奇怪,在return的时候返回,按说应该是正常的执行,没什么问题的呀。。。

在网上查到类似的错误不多,但找到一篇很有用的:http://stackoverflow.com/questions/1345670/stack-smashing-detected

原文如下:

Stack Smashing is actually a protection mechanism used by gcc to detect buffer overflow attacks.

An input of string greater than size 10 causes corruption of gcc inbuilt protection canary variable followed by SIGABRT to terminate the program.

You can disable this protection of gcc using option

即:stack smashing是GCC的一种检测“缓存溢出”的保护机制

并举例:如果在gets(array); 中,输入多于10个char,就会导致stack smashing错误

问题解决:

由于query语句比较长,所以也没检查char query[128]是否够用

在修改了query字符数组的长度为255之后,发现问题解决...

小结:

不只是在Linux下,在Windows下也有同样的状况。当分配的内存不够时,会继续执行;但是在程序结束返回时才出现错误提示。

0 0
原创粉丝点击