views:

149

answers:

5

I was going through one of the threads. A program crashed because It had declared an array of 10^6 locally inside a function.

Reason being given was memory allocation failure on stack leads to crash.

when same array was declared globally, it worked well.(memory on heap saved it).

Now for the moment ,Let us suppose, stack grows downward and heap upwards.

We have:

---STACK---

-------------------

---HEAP----

Now , I believe that if there is failure in allocation on stack, it must fail on heap too.

So my question is :Is there any limit on stack size? (crossing the limit caused the program to crash). Or Am I missing something?

+1  A: 

This all depends on what language and compiler you use. But programs compiled with for instance C or C++ allocate a fixed size stack at program startup. The size of the stack can usually be specified at compile time (on my particular compiler it default to 1 MB).

Andreas Brinck
I am using C/C++. Compiler is gcc.Windows Platform.Also I get no run-time error doing same on linux platform.I can comfortably declare an array of size 10^6 locally.So What about platform?
Vikas
+1  A: 

You don't mention which programming language, but in Delphi the compile options include maximum and minimum stack size, and I believe similar parameters will exist for all compiled languages.

I've certainly had to increase the maximum myself occasionally.

Cruachan
It is C/C++. Compiler-GCC. Platform:Windows.Also please read my comments below.
Vikas
@Vikas: Try not to refer by 'below'. The order of posts on SO isn't static.
Xavier Ho
@Xavier: Ohh ,I see.Thanx for the info. :)
Vikas
A: 

Yes, there is a limit on stack size in most languages. For example, in C/C++, if you have an improperly written recursive function (e.g. incorrect base case), you will overflow the stack. This is because, ignoring tail recursion, each call to a function creates a new stack frame that takes up space on the stack. Do this enough, and you will run out of space.

Running this C program on Windows (VS2008)...

void main()
{
    main();
}

...results in a stack overflow:

Unhandled exception at 0x004113a9 in Stack.exe: 0xC00000FD: Stack overflow.

Chris Schmich
yeah certainly It will give run-time error.But my doubt was: If the array declaration locally(on stack)caused runtime error.Why it escaped globally.means we have heap size limit greater than stack size.may be by default!!
Vikas
A: 

Maybe not a really good answer, but gives you a little more in depth look on how windows in general manages the memory: Pushing the Limits of Windows

Oliver
A: 

Yes, stack is always limited. In several languages/compilers you can set the requested size.

Usually default values (if not set manually) are about 1MB for current languages, which is enough unless you do something that usually isn't recommended (like you allocating huge arrays on the stack)

Foxfire