数组溢出导致的core dump

看这两段代码,哪个会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,谁能解释一下呢?

转载于:https://www.cnblogs.com/CalvinWang/p/5474395.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值