考虑下面的一段代码
#include <stdio.h> typedef struct{ int a[2]; double d; } struct_s; double fun(int i){ volatile struct_s s; s.d=3.14; s.a[i]=1073741824; printf("%f",s.d); return 0; } int main(){ fun(0); fun(1); fun(2); fun(3); fun(4); fun(5); // fun(6); // fun(7);在64位的ubunt上编译成a.out文件后执行,输出下列
3.1400003.1400003.1400002.0000013.1400003.140000可以看到fun(3)中对a的修改影响了d的值,不过这和CSAPP上讲的并不一样,CSAPP上认为fun(2)就会影响 至于fun(6)是无法运行的,如果放开fun(6)的注释后编译运行,会报下列错误
*** stack smashing detected ***: <unknown> terminated Aborted (core dumped)并且这个时候fun(0)到fun(5)也不会输出
另外上面的fun函数的参数是负数也是可以运行的,此时d的值任然是3.14