Reputation: 195
Using Visual Studio 2012, if I type the following:
char bytes[ 2*1024*1024*1024 ];
I get the error: "matrix size must be greater than zero". The same occurs if I declare the size dynamically, i.e.:
char* bytes = new char[ 2*1024*1024*1024 ];
If I remove the first "2", everything is fine. It seems as there's a hard limit on the amount of memory I can request either from the stack or the heap, being this limit 1 GB. However, given that size_t is 4 bytes in the worst case (it could be 8 bytes almost for sure), there is not any problem in the index not being able to address all the space of the array. Is the problem that the limit imposed to the stack and the heap is 1MB by default? (http://msdn.microsoft.com/en-us/library/f90ybzkh(v=vs.110).aspx). If this is the case, then why can I allocate 1 GB?
Upvotes: 0
Views: 918
Reputation: 212969
You need to take care not to overflow a 32 bit int expression - 2*1024*1024*1024
is 2^31
, which is 1 larger than INT_MAX
. Try:
char bytes[ 2ULL*1024*1024*1024 ];
Note that the compile error has nothing to do with stack or heap size. Whether you can actually allocate this amount of memory is a separate problem.
Upvotes: 4