views:

242

answers:

3

im trying to create an array: int HR[32487834]; doesn't this only take up about 128 - 130 megabytes of memory? im using MS c++ visual studios 2005 SP1 and it crashes and tells me stack overflow.

+6  A: 

While your computer may have gigabytes of memory, the stack does not (by default, I think it is ~1 MB on windows, but you can make it larger).

Try allocating it on the heap with new [].

Zifre
Nooooooooo. Use an RAII class that will allocate on the heap but has a defined lifetime and is exception safe. std::vector<int>
Martin York
why is the stack by default only ~ 1 mb? I did use the new operator and it worked. so why can it be allocated on the heap and not the stack?
TheFuzz
@Martin York: Using a vector would help!
Partial
@Martin York: you are correct that it would be good to use a `std::vector` and RAII if possible, but my main point was that it should be allocated on the heap. Since the OP said that he was trying to create an array, I suggested that.
Zifre
+3  A: 

The stack is not that big by default. You can set the stack size with the /F compiler switch.

Without this option the stack size defaults to 1 MB. The number argument can be in decimal or C-language notation. The argument can range from 1 to the maximum stack size accepted by the linker. The linker rounds up the specified value to the nearest 4 bytes. The space between /F and number is optional.

You can also use the /STACK linker option for executables

But likely you should be splitting up your problem into parts instead of doing everything at once. Do you really need all that memory all at once?

You can usually allocate more memory on the heap than on the stack as well.

Brian R. Bondy
Not only stack size, but also stack frame size come into play with these huge sizes (though I am not sure of the stack frame limitations on DevStudio).
Martin York
+10  A: 

Use a vector - the array data will be located on the heap, while you'll still get the array cleaned up automatically when you leave the function or block:

std::vector<int> HR( 32487834);
Michael Burr
Any reason for that weird space convention? (Sorry, but it makes my eyes bleed and I'm curious about purpose of it.)
Zifre
( x ) is too much white space and (x) isn't enough.
Michael Burr