首先我们先来看一段代码:
#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; //将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;
}
下面我们来看运行结果:
我们可以看到,由于结构体中的数组(顺序存储)最多放两个数,那么它的下标应该是0或1.当我们输入参数 1 时,3.14被正常显示出来,但当我们输入2 时,此时我们对前一个数组的访问已经越出范围,3.14显示为了3.1399998665,当输入数为3时,错的更离谱了。但4、5又正常显示了,这是因为我们访问的地址已经越过了3.14的存储地址了,所以输出没有受到影响。我的电脑在输入6时就显示“核心已转储”了,但有的电脑也可以一直运行下去,与电脑有关。
这是越界访问带来的错误。