I use malloc to create an array in C. But I got the segmentation fault when I tried to assign random values to the array in 2 loops.
There is no segmentation fault when I assign values to this array in 1 loop. The array size is large. Please see the code I attached. Anyone can give me a hint what is going on here. I am pretty new to C. Thanks a lot in advance.
int n=50000;
float *x = malloc(n*n*sizeof(float));
// there is segmentation fault:
int i, j;
for (i=0; i<n; i++){
for (j=0; j<n; j++){
x[i*n+j] = random() / (float)RAND_MAX;
}
}
// there is no segmentation fault:
int ii;
for (ii=0; ii<n*n; ii++){
x[ii] = random() / (float)RAND_MAX;
}