Programmatically find the maximum size of a static array in C ++

I am curious if it is possible to determine the maximum size an array can have in C ++.

#include <iostream> using namespace std; #define MAX 2000000 int main() { long array[MAX]; cout << "Message" << endl; return 0; } 

This compiles just fine, but then segfaults as soon as I run it (although the array is not actually referenced). I know that this is the size of the array, because if I change it to 1,000,000, it will work fine.

So, is there some way somewhere or somehow to have #define MAX MAX_ALLOWED_ARRAY_SIZE_FOR_MY_MACHINE_DEFINED_SOMEWHERE_FOR_ME ?

In fact, I do not need this, it is a question for the sake of curiosity.

+8
c ++ memory
source share
4 answers

There is no way to determine this statically, because the actual limit depends on how much stack was allocated by your thread. You can create a new stream, give it 10 megabytes of stack, and you can allocate a correspondingly larger local array.

The amount you can allocate on the stack also depends on how much has been used so far.

+10
source share
 void foo(int level){ int dummy[100]; cerr<<level<<endl; foo(level+1); } 

Then, perhaps you can multiply the last print level by 400 bytes. Recursive calls take up most of the stack space, I think, but you can get a lower bound. I can skip some understanding of memory management here, so it’s open for corrections.

So this is what I got on my machine with different size of the dummy array.

 level array size stack total 24257 100 9702800 2597 1000 10388000 260 10000 10400000 129 20000 10320000 64 40000 10240000 25 100000 10000000 12 200000 9600000 
+4
source share

Most variables declared inside functions are allocated on the stack , which is basically a fixed-size memory block. Attempting to allocate a stack variable larger than the stack size will cause a stack overflow, which causes segfault.

Often, the stack size is 8 MB, so on a 64-bit machine, long max[1000000] has a size of 8*1000000 < 8MB (the stack is "safe"), but long max[2000000] has a size of 8*2000000 > 8MB , so the stack overflows and segfaults program.

On the other hand, dynamically allocating an array using malloc puts the memory in a heap that is basically unlimited (4 GB on a 32-bit machine, 17,179,869,184GB on a 64-bit machine).

+2
source share

Read this to understand the limitations set by the hardware and the compiler. I don’t think you can have MAX installed for you to use it right away.

+1
source share

All Articles