user415789
user415789

Reputation:

simple array cause exception

#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?

Upvotes: 2

Views: 2529

Answers (4)

TonyK
TonyK

Reputation: 17114

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.

Upvotes: -1

Gene Bushuyev
Gene Bushuyev

Reputation: 5538

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.

Upvotes: 0

Charles Salvia
Charles Salvia

Reputation: 53289

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

Upvotes: 7

Zac
Zac

Reputation: 3285

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

Upvotes: 1

Related Questions