Error accessing pointers when succesfully allocated array is too big

你离开我真会死。 提交于 2019-12-07 18:02:26

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!