Question

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 ^^

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top