0

I wrote down this very very simple C++ program which I compile with clang++ using the following command and it crashes:

clang++ -O3  test.cpp  -o test -g

source:

int main(int argc, char **argv)
{
    class TestVec3
    {
            public:
            TestVec3()  { x = y = z = 0; }
            float x, y, z;
    };

    TestVec3 colorBuffer[1000 * 1000];

    return 0;
}

when I use llbb I get:

* thread #1: tid = 0x2529bd, 0x0000000100000f40 perspprojmat`main [inlined] TestVec3 at ridiculous.cpp:8, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=2, address=0x7fff5f08e088)
frame #0: 0x0000000100000f40 perspprojmat`main [inlined] TestVec3 at ...
   5        class TestVec3
   6        {
   7            public:
-> 8            TestVec3()  { x = y = z = 0; }
   9            float x, y, z;
  10        };
  11    

I haven't programmed in a while but that sounds just ridiculous? What am I missing which is that obvious. If I do a dynamic allocation, it works? (using new). Thanks for your help.

user18490
  • 3,546
  • 4
  • 33
  • 52
  • 2
    You're allocating almost 12MB (assuming `float` is four bytes) on the stack with that array, that's much more than the standard stack on just about any system (which usually in the single-digit territory), – Some programmer dude Jan 16 '15 at 23:06
  • Cool that interesting answer and I am ready to accept it. How can I know the limit I can allocate on the stack that way? – user18490 Jan 16 '15 at 23:08
  • It depends, but when something starts to take several tens of KB then you should start thinking about it. Yes, that little, the stack is limited, and is shared for all functions called. If you want to allocate large amounts of data, use the heap – Some programmer dude Jan 16 '15 at 23:10
  • Make sense I really appreciate this answer. Please make this as a proper answer and I will accept it. – user18490 Jan 16 '15 at 23:11
  • 1
    Can also query with: `ulimit -s` – Brett Hale Jan 16 '15 at 23:27
  • There are already *hundreds* of answers and questions on this same subject. [for example](http://stackoverflow.com/questions/1847789/segmentation-fault-on-large-array-sizes), or another [here](http://stackoverflow.com/questions/7902228/segmentation-fault-large-arrays), or [here](http://stackoverflow.com/questions/4220965/segmentation-fault-due-to-lack-of-memory-in-c), etc. – WhozCraig Jan 17 '15 at 02:24
  • I know, I just don't know how I could have found that by doing a research, without thinking it was a problem with allocating memory on the stack. I did search for a while though. – user18490 Jan 17 '15 at 13:21

0 Answers0