成功分配的数组太大时访问指针时出错 [英] Error accessing pointers when succesfully allocated array is too big

查看:195
本文介绍了成功分配的数组太大时访问指针时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下非常简单的代码,它完美地工作:

  void func(int * tab)
{
return;
}

int main()
{
int maxsize = 999 * 999;
int tabs [maxsize] [6];

return 0;
}

然而,当我修改主要使我获得这个,它崩溃。

  int main()
{
int maxsize = 999 * 999;
int tabs [maxsize] [6];

func(tabs [0]);

return 0;
}

你有什么想法为什么吗?非常感谢您的帮助,谢谢^^

解决方案

所以虽然标准没有谈到堆栈最现代的实现将在堆栈上放置自动变量,堆栈通常在 1M 8M 之间你会溢出你的数组大小。您可以在此处找到不同系统的典型堆栈大小:

  SunOS / Solaris 8172K字节
Linux 8172K字节
Windows 1024K字节
cygwin 2048K字节

第一个不区分故障的原因是因为编译器实际上不需要引用任何内存,如果你需要引起一些副作用,那么编译器生成一个内存访问,这将导致实际的堆栈溢出。因为你说你使用 gcc 如果我运行这个代码没有任何副作用( live example )它实际上会调整堆栈指针,但从不使用它:

  subq $ 23952048,%rsp 

但如果我们通过 std :: cin std :: cout live example ):

  std :: cin>>标签[maxsize-1] [5]; 
std :: cout<< tabs [maxsize-1] [5]< std :: endl;

那么它将需要使用堆栈指针:

  leaq 3(%rsp),%rbx 

通常会在类Unix系统上产生 seg错误



注意,此警告:

 警告:ISO C ++禁止可变长度数组'tabs'[-Wvla] 

这是因为可变长度数组不是标准的 C ++ (但在 C99 中有效)是 gcc扩展,当使用 -pedantic 时, / p>

I have this following very simple code, that works perfectly:

void func(int *tab)
{
    return;
}

int main()
{
    int maxsize = 999*999;
    int tabs[maxsize][6];

    return 0;
}

However, when I modify the main such that I obtain this, it crashes.

int main()
{
    int maxsize = 999*999;
    int tabs[maxsize][6];

    func(tabs[0]);

    return 0;
}

Do you have any idea why? I would really appreciate your help on this, thank you ^^

解决方案

So although the standard does not talk about stacks most modern implementations will put automatic variables on the stack and the stack will typically between 1M and 8M which you will overflow with your array size. You can find typical stack sizes for different system here:

SunOS/Solaris   8172K bytes
Linux           8172K bytes
Windows         1024K bytes
cygwin          2048K bytes

The reason why the first one does not seg fault is because the compiler does not actually have to reference any memory but if you need to cause some side effect then the compiler generate a memory access which will cause an actually stack overflow. Since you said you are using gcc if I run this code without any side effects(live example) it will indeed adjust the stack pointer but never uses it:

subq    $23952048, %rsp

but if we add a side effect via std::cin and std::cout (live example):

std::cin >> tabs[maxsize-1][5] ;
std::cout << tabs[maxsize-1][5] << std::endl ;

then it will require the use of the stack pointer:

leaq    3(%rsp), %rbx

which will usually generate a seg fault on Unix-like systems.

Note, you may also notice this warning:

warning: ISO C++ forbids variable length array ‘tabs’ [-Wvla]

That is because variable length arrays are not standard C++ (but are valid in C99) are a gcc extension and when using -pedantic it will warn when you are using extensions.

这篇关于成功分配的数组太大时访问指针时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆