0

I can find plenty of examples of developers complaining that a big array initialized on the stack create a stack overflow error

int main(int argc, const char * argv[])
{
    int v[100000000];
    memset(&v, 0, sizeof(v));
}

When compiling on Apple LLVM 7.0, this does not cause a stack overflow, this puzzles me as the array has a size of ~400Mb, significantly more than what is usually the size of the stack.

Why does the above code not cause stack overflow?

13
  • 5
    and how did you check your stack size on your environment? Commented Feb 8, 2016 at 16:47
  • 6
    Dunno anything about LVVM but if I were a compiler, I would ignore that no-op Commented Feb 8, 2016 at 16:49
  • Just because declaring a large array on the stack risks causing a stack overflow does not mean that you can rely on it to do so. Commented Feb 8, 2016 at 16:49
  • Why would that array even exist? Commented Feb 8, 2016 at 16:50
  • 2
    as the array has a size of 100Mb. it is sizeof(int)*100M actually Commented Feb 8, 2016 at 17:00

2 Answers 2

2

Since you are not using v then probably the compiler is not allocating it, try something like

int v[100000000];
for (int i = 0 ; i < sizeof(v) / sizeof(*v) ; ++i)
    v[i] = 0;
Sign up to request clarification or add additional context in comments.

5 Comments

Perhaps v[rand()%100000000] = 0; and then read the array somehow.
or you can use memset
@terencehill I know, it would requiere including string.h and I think the loop is more verbose.
@terencehill even memset may be ignored. Under Windows for example, you should use SecureZeroMemory if you want your zero-isation be not optimized, typically used to clear a password: msdn.microsoft.com/fr-fr/library/windows/desktop/…
@mikedu95 But I guess it will not be ignored without optimisation. I added a comment above, on my MAC even setting only the first element results in a segmentation fault.
0

Your array is more than 100 Mb (*) but assuming it is 100 Mb, that means that either your stack size is larger than 100 Mb, or either your compiler ignored it because you do not use it. That's a compiler optimization.

(*) Indeed 1M = 1024 * 1024, not 1000 * 1000. And one int is more than 1 bit, more than 1 Byte too. And finally, Mb means Megabit and MB means Megabyte.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.