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

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

问题描述

我有这下面很简单code,完美的作品:

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;
}

你有任何想法,为什么?我真的AP preciate您对此帮助,谢谢^^

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

推荐答案

因此​​,尽管标准不谈论堆栈最现代化的实现将投入的自动变量的堆栈上,堆栈通常会之间 1M 800万,你将与你的数组大小溢出。你可以找到不同的系统中的典型堆栈大小 rel=\"nofollow\">:

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

为什么第一个不赛格故障的原因是因为编译器实际上并没有引用任何记忆,但是如果你需要引起一些副作用,那么编译器生成内存访问,这将导致实际堆栈溢出。既然你说你正在使用 GCC 如果我运行此code,无任何副作用(活生生的例子 的),它的确会调整堆栈指针,但从来没有使用它:

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

但如果我们通过的std :: CIN 的std :: COUT 添加一个副作用( 活生生的例子 的):

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

这通常会产生的赛格故障的上的类Unix系统

请注意,你可能也注意到这样的警告:

Note, you may also notice this warning:

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

这是因为变长数组不是标准的 C ++ (但在有效的 C99 的)是一个 GCC扩展并用时 -pedantic 当您使用扩展它会发出警告。

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天全站免登陆