代码功能
模拟缓冲区的溢出情况。
代脉内容
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int a[2];
double d;
} struct_t;
double fun(int i) {
volatile struct_t s;
s.d = 3.14;
s.a[i] = 1073741824; /* Possibly out of bounds */
return s.d; /* Should be 3.14 */
}
int main(int argc, char *argv[]) {
int i = 0;
if (argc >= 2)
i = atoi(argv[1]);
double d = fun(i);
printf("fun(%d) --> %.10f\n", i, d);
return 0;
}
运行结果
结果分析
i = 0、1时,因为定义数组能使用部分只有a[0]和a[1],故输出正常。
i = 2、3时,机器访问内存的时候跨过了数组本身的界限去修改了 d 的值,所以输出的不是3.1 4而是随机的值。
i = 4、5时,越过了double d的空间而继续存储,输出正常。
i = 6时,超出了栈的范围,无法输出。