I am trying to save a 2D Array that is populated using a function to global memory. Many matrices are processed and upon success, the correct Matrix needs to be saved for access to numerous functions.
Currently, the matrix within the function is dynamically allocated with the following code:
int **M = malloc(m * sizeof(int *));
for(i = 0; i < m; i++)
M[i] = malloc(n * sizeof(int));
I have a global variable declared (int **M_save). In the main program when the matrix needs to be saved, the global array is initialized using the same procedure:
**M_save = malloc(m * sizeof(int *));
for (i = 0; i < m; i++)
M_save[i] = malloc(n * sizeof(int));
The function is then notified that it needs to save the matrix before it frees its memory and the following procedure is used in the function to save:
if(saveMatrix == 1) {
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
M_save[i][j] = M[i][j];
}
}
}
When running the program I receive a segmentation fault when the values are being copied (M_save[i][j] = M[i][j]). I am not sure what I am doing wrong.
I checked to make sure than m and n are the same size for both array and after I am done using the matrices they are freed from memory with the following code:
for(i = 0; i < m; i++) {
free(M[i]);
}
free(M);
M_save = M?