0

I have a fairly simple code that assigns double values to two arrays, then takes the outer product of them. Here is the code:

int i, j;

double A[1000][1000];
double B[1000][1000];

for (i = 0; i < 1000; i++) {
    for(j = 0; j < 1000; j++) {
        A[i][j] = (double)rand()/(double)RAND_MAX;
        B[i][j] = (double)rand()/(double)RAND_MAX;
        // Segmentation fault occurs in here somewhere.
    }
}

// Take outer product, not even saving the result at this point

I understand that the Segmentation fault might occur when there is no memory left which is backed up by the fact that I only get the error for arrays above 723x723. What doesn't make sense is that two 1000x1000 arrays of double values don't come close to my 16GB memory and two 723x723 arrays is already bigger than the cache. Further more, the error occurs while initializing values, if the arrays are too large, wouldn't it complain while declaring them?

Suggestions anyone?

EDIT: After some more debugging, I found that I can't access any element of the arrays if they are too large i.e.

A[0][0] = 1.0;

Also causes the Segmentation fault.

UPDATE: I have tried replacing the declaration to global by using:

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

and:

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

In both cases, it will now give the Segmentation fault no matter the array size.

Making the arrays static works but only if I hard code the size into it, otherwise the compiler complains that "variable length array declaration cannot have 'static' storage duration"

SOLVED: A bit silly but just needed to do the global declaration as follows:

double **A = maloc(size * sizeof *A);
for (i = 0; i < size; i++) {
    A[i] = maloc(size * sizeof *A);
}

Not exactly sure why but that's just because I am quite new to c

Devman
  • 310
  • 2
  • 10

0 Answers0