看这两段代码,哪个会core呢?
#include <stdio.h>
int main()
{
int stack_of[100000000];
int* a;
a = stack_of;
a[99999999] = 0xff;
return(0);
}
#include <stdio.h>
int main()
{
int stack_of[100000000];
int* a;
a = stack_of;
a[0] = 0xff;
return(0);
}
答案是第二段代码会core。原因很简单栈空间是从高地址向低地址延伸的,Linux的写时拷贝技术决定了在数组元素赋值前并不会真正的在栈上分配空间。但是一旦分配a[0]的空间,那么从0到99999999都需要分配。这个数值大于Linux默认的栈大小8M,自然就core了。反之如果在a[99999999]分配则没有问题。
再看一段代码
#include <stdio.h>
int main()
{
int stack_of[100000000];
int b=1;
int* a;
int i = 0;
int j = 0;
a = stack_of;
for(i = 99999999;i > 0; i--, j++)
{
a[i] = 0xff;
printf("Have used %d bytes.\n", j*4);
}
return(0);
}
问输出是什么,会有几次打印?
答案一次都不会有,直接core。当数组在循环中时,无论从哪个数组元素开始,栈上的空间都会完全分配好,所以直接就core了。
最后再看一个代码
#include <stdio.h>
int main(void)
{
int *m;
int i = 0;
int a = 1;
int b[10];
printf("The address of i is %x\n", &i);
printf("The address of a is %x\n", &a);
printf("The value of a is %d\n", a);
printf("The address of b is %x\n", b);
for(i=9; i>=0; i--)
{
b[i]=i;
printf("The address of b[%d] is %x\n",i, &b[i]);
}
m=&b[10];
printf("Now we do something mess\n\n");
printf("The address of m is %x\n", m);
*m=2;
printf("The value of a is %d\n", a);
while (1)
{
printf("Have not cored\n");
m++;
printf("Now the address is %x\n", m);
*m=1;
}
}
输出结果如下:
The address of i is bfff00d8
The address of a is bfff00d4
The value of a is 1
The address of b is bfff00ac
The address of b[9] is bfff00d0
The address of b[8] is bfff00cc
The address of b[7] is bfff00c8
The address of b[6] is bfff00c4
The address of b[5] is bfff00c0
The address of b[4] is bfff00bc
The address of b[3] is bfff00b8
The address of b[2] is bfff00b4
The address of b[1] is bfff00b0
The address of b[0] is bfff00ac
Now we do something mess
The address of m is bfff00d4
The value of a is 2
Have not cored
Now the address is bfff00d8
Have not cored
Now the address is bfff00dc
Have not cored
Now the address is 5
Segmentation fault (core dumped)
可以看到m的指针成功的向上覆盖到了局部变量a的地址,并把a的值给修改了。最后延伸出栈的地址后发生core。比较有趣的是延伸出去后m的地址是5,谁能解释一下呢?