I am running my code using n = 2. I have been trying to research, but I do not get why I obtain different outputs when I try to run my code several times. Under you can see my output when I run with n = 2, and my txt.file contains 73 characters in each row, and consist of 4 rows.
This is my output the first time and run and is the expected and wanted output
This is the output the second time I run the code
This is the output the third time I run the code
I do not know what to do to prevent the errors happening in image 2 (where you have a \274 in the second printed line) and but specially with errors I get the third time running the code. Do i have to use MPI_Allocate? Am I freeing the matrix to early?
This is my code:
#define MAXCHAR 73
#define MAXLENGTH 100
int main(int argc, char** argv) {
FILE *fp;
char* filename = "/Users/test.txt";
char *line = malloc(MAXCHAR);
char (*matA)[MAXCHAR] = NULL;
char str[MAXCHAR];
int rowCount, num_rows, i, my_id,
root_process,num_procs,rows_per_process;
MPI_Init(&argc, &argv);
root_process = 0;
/* find out MY process ID, and how many processes were started. */
MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
// READ TXT FILE INTO DYNAMIC ARRAY
if(my_id == root_process){
fp = fopen(filename, "r");
if (fp == NULL){
printf("Could not open file %s",filename);
return 1;
}
//NUMBER OF lines
size_t count=1000;
rowCount=0;
while(getline(&line, &count, fp)!=-1) {
rowCount++;
}
//REWIND file
rewind(fp);
matA = malloc(rowCount*sizeof(matA));
i = 0;
while (fgets(str, MAXCHAR, fp) != NULL){
for (size_t j = 0; j < MAXCHAR; j++) {
if(str[j] == '\n'){
continue;
}
matA[i][j] = str[j];
}
i++;
num_rows = i;
}
fclose(fp);
}
// BCAST rowCount to Calculate rows each process will receive
MPI_Bcast(&rowCount, 1, MPI_INT, 0, MPI_COMM_WORLD);
rows_per_process = rowCount/num_procs;
char(*part_matrix)[MAXCHAR];
part_matrix = malloc(rows_per_process*sizeof(*part_matrix));
MPI_Scatter(&(matA[0][0]), rows_per_process*73, MPI_CHAR, &(part_matrix[0][0]), rows_per_process*73, MPI_CHAR, 0, MPI_COMM_WORLD);
printf("Process %i received %i rows:\n", my_id, rows_per_process);
// PRINTING
for (size_t i = 0; i < rows_per_process; i++) {
printf("PROCESS %i PRINTS LINE NUMBER %zu:\n", my_id, i);
for (size_t j = 0; j < MAXCHAR; j++) {
printf("%c", part_matrix[i][j]);
}
printf("\n" );
}
free(part_matrix);
MPI_Finalize();
return 0;
}