Compilation error: Can't allocate array with constant size 0. Why am I getting this?

I ran into one problem while working on C code with the Microsoft Visual Studio-2005 compiler.

I tried to declare the large buffer statically like:

int gbl_data[4096*4096*256]; 

      

EDIT: This declaration was a global variable in the header file.

It gave a compilation error: " cannot allocate array with constant size 0 ".

So the size 4096X4096X256 becomes too large than the size MAX_INT_LIMIT (2 ^ 31) and can wrap around and become -ve or so. But then he had to give the error as "negative index".

I tried casting constants like 4096UL x 4096UL x 256UL, still the same compilation error.

What is the reason for this error?

Is it because the size of the physical memory is dropping to allocate this large buffer or what?

What is this fix?

Thanks.

-GM.

+1


a source to share


2 answers


The size of the array is not int, it is unsigned int. The maximum unsigned int is 4294967295. You have another one and it wraps around to 0.

Casting constants as longs doesn't change anything, because longs are also 32-bit integers on most platforms.

You can try with long long ones instead, but now we have another small problem.



You are trying to allocate 4 billion integers. A 32-bit processor has 4 billion bytes of memory. You are trying to allocate 4 times the maximum theoretical memory that can exist. (16 GB)

So, back to the drawing board. Find out why you were trying this and what you can do instead.

+9


a source


You are trying to statically allocate an array of 2 ^ 32 (or 4 times the address space on a 32-bit system). The compiler appears to truncate 4096 * 4096 * 256 (which, in my head, is 0x10000) to a 32-bit value.

Depending on your platform, unsigned long can also be 32 bits and also truncated.



I would advise you to make sure you are compiling for a 64-bit platform (if that's what you intend), or change the algorithm to either dynamically allocate memory (obviously no more than an address space), or to wok with files on disk.

0


a source







All Articles