0

I wrote the following C++ code. It is compiled on Windows 8 with MinGW (from msys). If I run it Windows will stop it and give a stack overflow error (C00000FD). What's the problem?

#include <iostream>
using namespace std;

class Test{
  public:
    int txt[1000];
};

int main(){
  Test a[1000];
  return 0;
}

What should I do, say, if I want to store a picture the size of 1920*1080? It'll be 1920*1080*4 bytes.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Xun Yang
  • 4,209
  • 8
  • 39
  • 68

3 Answers3

4

I believe that the default stack size in Windows is 1MB. As you are allocating 1000^2 ints, each of which is 4 bytes large, you trying to put more on the stack than it can hold.

  • To make it more explicit: `a` is 4MB, your stack is 1MB. Trying to put 4MB of stuff into a 1MB room leads to overflow... – Cornstalks Nov 10 '14 at 16:55
1

Each Test object contains 1000 integers, likely clocking in at about 4kb each.

In main you are creating an array of 1000 objects for a total of 4MB. Your stack can't hold 4 megs.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms686774%28v=vs.85%29.aspx says a common default is 1MB.

Note that

std::vector<Test> a(1000);

Will probably work just fine. std::vector does not store its contents on the stack like a local array does.

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
0

The Test object is at least 4000 bytes in size (depending on your platform's int size). You are trying to create an array of 1000 Test objects which will be 4,000,000 bytes or nearly 4 MB. This almost certainly exceeds the default stack size for your program. You could possibly change this with some compiler options, but the question should really be what are you trying to do?

You should store large objects on the heap instead of the stack.

You can in fact change the default stack size with the following option in MinGW according to this answer:

gcc -Wl,--stack,N

But again, the better thing to do is to not store your large objects on the stack.

Community
  • 1
  • 1
b4hand
  • 9,550
  • 4
  • 44
  • 49