Question

I need to declare an array of size LONG_MAX (2147483647, in the c library <limits.h>), and I really need this for solving a problem. But the code gives me and error: if I write long int v[LONG_MAX]; the compiler gives size of array 'v' is too large. How can I solve this problem?

Was it helpful?

Solution

On pretty much every system that exists, variables that are declared as local arrays with a fixed size are placed on the stack.

The C standard (5.2.4.1) only guarantees that programs running on an OS should be able to hold an object of size 65535 bytes. And no matter what the standard says, the OS will set a stack limit for your process.

If you declare a object that is too large, as far as the C standard is concerned, you get the compiler error you describe. Otherwise, if you pass that check but still use up too much stack, with nested function calls etc, you get a runtime error: stack overflow.

The preferred way to solve this is to always allocate large objects using dynamic memory allocation. Then the objects are allocated on the heap, and the RAM of your the computer pretty much sets the limit.

OTHER TIPS

If you have to use so large memory, which is do not allowed to allocate by system, you can use memory mapping instead.

fd=open(name, flag, mode); 
if(fd<0) 
   ... 
ptr=mmap(NULL, len , PROT_READ|PROT_WRITE, MAP_SHARED , fd , 0);

// use the virtual memory that ptr pointed to, like what you do with arrays.
...

munmap( p_map, len); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top