Hi all,
I'm getting segmentation fault errors when I try to send/receive 2 rows of a matrix as a block, and I can't figure out why.
Basically, I have a 4x5 matrix with an extra top row and an extra leftmost column, making it a (4+1)x(5+1) matrix stored in P0. I'm trying to send the 2nd and 3rd row as a block to P1, print out the contents, send the 4th and 5th row as a block to P1, then print out the contents again. I have dynamically allocated a (4+1)x(5+1) memory block to cellblock, then used the pointers cell[i] to point to each "row" of cellblock, so I can access the 2D array by cell[i][j].
I get the correct output, but with segmentation fault at the end.
Here is my code:
Please advise. Thank you.Code:#include <stdio.h> #include <stdlib.h> #include <mpi.h> int main(int argc, char** argv) { int rank, i, j, k = 1; int **cell, *row1, *cellblock; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); row1 = (int*)calloc((5+1) * 2, sizeof(int)); cellblock = (int*)calloc((4+1)*(5+1), sizeof(int)); cell = &cellblock; for (i = 0 ; i < (4+1) ; i++) cell[i] = &cellblock[i*(5+1)]; if (rank == 0) { for (i = 0 ; i < (4+1) ; i++) for (j = 0 ; j < (5+1) ; j++) cell[i][j] = k++; for (i = 1 ; i < 5 ; i+=2) MPI_Send(&(cell[i][0]), (5+1)*2, MPI_INT, 1, 1, MPI_COMM_WORLD); } if (rank == 1) { for (i = 0 ; i < 2 ; i++) { MPI_Recv(row1, (5+1)*2, MPI_INT, 0, 1, MPI_COMM_WORLD, &status); for (j = 0 ; j < (5+1)*2 ; j++) printf("%d ", row1[j]); printf("\n"); } } free(row1); free(cellblock); MPI_Finalize(); return 0; }
Regards,
Rayne
You have several problems with your code that you need to fix.
(1) You're allocating your matrix wrong. Do this:
(2) The reason why you're getting a segmentation fault is because you're freein part of an array and then trying to free the entire array. That's a no-no. Contrary to what you might believe, cell and cellblock are actually pointing to the same memory.Code:int **matrix = (int **)calloc(numberOfRows,sizeof(int *)); for(int i = 0; i < numberOfColumns; ++i) matrix[i] = (int *)calloc(numberOfColumns,sizeof(int));
(3) I have no idea what you're doing with the for loop in lines 15-16, but it appears that you're copying values in an array on top of themselves. Again, I think it's because you think that cell and cellblock are different. They're not.
(4) Try putting comments in your code, because as of right now, I have no idea what's going on in your if(rank==...) section. That might also be a part of the problem.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks