2
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    float x[1000][1000];

    return 0;
}

I get " First-chance exception at 0x01341637 in s.exe: 0xC00000FD: Stack overflow." why?

2

4 Answers 4

7

Your array is simply too large to fit on the stack. You don't have enough stack space for 1000 * 1000 elements.

You'll need to allocate your array on the heap. You can do this using the new keyword, but an easier way is to just use std::vector.

std::vector<std::vector<float> > floats(1000);
for (unsigned i = 0; i != floats.size(); ++i) floats[i].resize(1000);

This will give you a two-dimensional vector of floats, with 1000 elements per vector.

Also see: Segmentation fault on large array sizes

Sign up to request clarification or add additional context in comments.

12 Comments

@HPT - one solution is to use dynamically allocated memory, or use something like a vector of vector.
You can also do a static array of dynamic arrays (aka an array of pointers). Just be aware that the dynamic arrays won't be contiguous in memory.
You could also just make the array static. This should be fine.
no need to write loop when the library does it for you: std::vector<std::vector<float> > floats(1000, std::vector<float>(1000, 0.0));
@TonyK: not in my experience. It usually just leads to more moving stuff around until it works. Repeat until moving stuff around no longer makes it work, at which point the "programmmer" usually gives up.
|
1

float is 4 bytes, so 4 * 1000 * 1000 = 4 megabytes.

"stack size defaults to 1 MB"

See here: http://msdn.microsoft.com/en-us/library/tdkhxaks(v=VS.100).aspx

3 Comments

really, you should probably use some sort of dynamic container, like @birryee is suggesting.
Approx 3.8 megabytes. With the assumption that sizeof(float) == 4
This also assumes you're using Windows and MSVC.
0

As others explained, the size of the object is bigger than the (default) size defined for function stack frame. There are two solutions: 1) create an object on the heap, which is likely to be bigger; or 2) increase the function stack frame size, which can be problematic in 32-bit environment, because you can run out of addressable space, but it can easily be done in 64-bits.

Comments

-1

Just declare your array static:

static float x[1000][1000];

Edited to add:

Sigh Another silent downvoter. Not that I'm surprised. This is obviously the simplest solution to OP's problem, so it violates the prime tenet of the OOP Komissariat: The simplest solution is always wrong.

Comments

Your Answer

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