0

I'm trying to make an one-dimension array with 89401 elements in C:

double **A = (double**)malloc(89401*sizeof(double*)); 

for (i = 0; i<89401; i++)       

    A[i] = (double*)malloc(89401*sizeof(double));

But I keep getting this error:

Exception thrown at 0x003F61E0 in final project 2.exe: 0xC0000005: Access violation writing location 0x00000000.

I can't figure out what's the problem. I searched the site for previously asked questions but none of them contributed to me.

If there is a handler for this exception, the program may be safely continued.

Jair López
  • 650
  • 1
  • 5
  • 16
yonatan
  • 113
  • 9
  • Please check if `A` is not `NULL` before trying to assign something to elements of what is pointed by it. – MikeCAT Jun 12 '16 at 15:10
  • 1
    If `sizeof(double)` is 8, This wil request about 59.5GB of memory. Does your system have sufficient RAM (+ swap) to store this big data? – MikeCAT Jun 12 '16 at 15:12
  • 1
    **Always** check for error results from function which are relevant for program execution. Also don't cast the result of `malloc` & friends or `void *` in general in C! – too honest for this site Jun 12 '16 at 15:14
  • 3
    [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Jun 12 '16 at 15:21

1 Answers1

1

You have made two mistakes. The first is, that you said, you try to create "1d array in the size of 89401". In fact you try to allocate 89401*89401 doubles, which seems 2D array. As @MikeCAT wrote this is a huge number, 89401*89401*8 bytes, if you have 8 byte doubles. The second is that you do not handle when the memory allocation by malloc is not successful, i.e. when the result is NULL.

quantummind
  • 2,086
  • 1
  • 14
  • 20