相邻变量内容互相干扰的一个例子
2003-5-3
程序用例:
void main()
{
char addrA[5], addrB[5];
printf("the address of addrA is: %d\n", &addrA);
printf("the address of addrA[4] is: %d\n", &addrA[4]);
printf("the address of addrB is: %d\n", &addrB);
printf("the address of addrB[4] is: %d\n", &addrB[4]);
scanf("%s", addrA);
scanf("%s", addrB);
printf("addrA: %s\n", addrA);
printf("addrB: %s\n", addrB);
}
编译器
GNU C++
运行平台:
WIN2000
运行结果:
the address of addrA is: 2293616
the address of addrA[4] is: 2293620
the address of addrB is: 2293600
the address of addrB[4] is: 2293604
abcd
abcdefghijklmnopqrstuvwxtyzl
addrA: qrstuvwxtyzl
addrB: abcdefghijklmnopqrstuvwxtyzl
几点结论:
1、系统按变量出场次序从高址往低址依次分配内容。
2、两个变量之间保留12个字节的缓冲区。
3、C/C++语言不检查数组的边界,这是导致错误的根本原因。