1

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);
3
  • can't you just do a M_save = M? Commented Oct 20, 2011 at 17:19
  • I don't believe you can assign complete arrays to each other in that manner using C. To copy values you must iterate through the array and save each value. Commented Oct 20, 2011 at 19:07
  • But it's not an array, @milbert, it's actually a pointer. Commented Oct 20, 2011 at 20:00

1 Answer 1

1

The solution turned out to be very simple. The matrix was defined globally as

int **M_save;

I was assigned it in main using the following:

**M_save = malloc(m * sizeof(int *));
for (i = 0; i < m; i++)
    M_save[i] = malloc(n * sizeof(int));

Instead I should have been using

M_save = malloc(m * sizeof(int *));
for (i = 0; i < m; i++)
    M_save[i] = malloc(n * sizeof(int));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.