【发布时间】:2015-05-25 14:38:32
【问题描述】:
我知道这是危险行为,但我想弄清楚发生了什么。
代码如下:
#include<stdio.h>
#include<stdlib.h>
static int count = 0;
void hello(void){
count ++;
fprintf(stderr,"hello! %d\n",count);
}
void foo(void){
void *buf[10];
static int i;
for(i = 0 ; i < 100 ; i++){ // put enough data to overwrite the return address on the stack
buf[i] = hello;
}
}
int main(void){
int buf[1000];
foo();
return 0;
}
结果如下:
……
hello! 83
hello! 84
hello! 85
hello! 86
hello! 87
hello! 88
hello! 89
Segmentation fault (core dumped)
为什么 hello 函数被调用了 89 次?
当函数foo返回时,pc寄存器应该得到hello函数的地址,不是吗?
于是调用了hello,执行了里面的代码,然后呢?程序不应该返回主函数吗? “89”从何而来?我似乎遗漏了什么,请有人指出来。
【问题讨论】:
-
您使用的是哪个编译器/操作系统?另外,你知道 main 中的 buf 和 foo 中的 buf 没有任何关系,对吧?
-
@Ashalynd centos 7, gcc
-
哪个版本的 gcc?
-
@Ashalynd gcc (GCC) 4.8.2 20140120(红帽 4.8.2-16)
-
你自己说你覆盖了返回地址,所以
main不能被返回。你的程序“返回”到hello,直到它崩溃。
标签: c++ c stack-overflow