Search code examples
carrayspointersmallocdynamic-memory-allocation

Access violation on try to fill dynamic array (large number of items)


I have the following C code:

int dimension; 
double *AtS;
...
AtS=(double*)malloc(sizeof(double)*dimension); 

for (i=0; i<dimension; i++)
{
  AtS[i]=0.0; 
}

While dimension is ~6-8 millions it works fine, but when it about 300 millions it fails with access violation. The following message in debug:

Unhandled exception at 0x012f1077 in mathpro.exe: 0xC0000005: Access violation writing location 0x00000000.

The same situation if I use memset() instead of cycle.

Are there any ideas how it's resolve this problem?


Solution

  • "Access violation writing location 0x00000000" is explained by the manual

    http://man7.org/linux/man-pages/man3/malloc.3.html#RETURN_VALUE

    On error, these functions return NULL.

    Or if you prefer http://www.cplusplus.com/reference/cstdlib/malloc/.

    Return Value

    On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. If the function failed to allocate the requested block of memory, a null pointer is returned.

    You have encountered an error. Quite likely out of memory.

    If you were to inspect the value sizeof(double)*dimension prior to passing it to malloc, you'll find that it is indeed quite a large number.