1

I want to send message(greeting) from 0 process to 1-6 process, and add the number i behind the message every time(G_str), but the result shows that

processor 1 received string:  from processor 0 
processor 2 received string:  from processor 0 
...

I don't know it didn't show the message I want to send

#include <stdio.h>
#include <string.h>
#include <mpi.h>

int main(int argc, char *argv[])
{
    int PID, P;
    char greeting [] = "hello";
    char replying [] ="nice to see you";
    char G_str [10];
    char R_str [10];

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &P);
    MPI_Comm_rank(MPI_COMM_WORLD, &PID);

    int len_g = strlen(greeting);
    int len_r = strlen(replying);
    int len_G = strlen(G_str); 
    //send and receive//

    if (PID == 0){

        for (int i = 1; i <= 6; i++)
        {   
            sprintf(G_str, "%s%d", greeting,i);              
            MPI_Send(&G_str, len_G, MPI_CHAR, i, 77, MPI_COMM_WORLD);
        }
    }
    else{    
        MPI_Recv(&G_str, len_G, MPI_CHAR, 0, 77, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        printf("processor %d received string %s from processor 0 \n", PID, G_str);      
    }

    MPI_Finalize();

}

I guess the problem is on the length of G_str, but how to correct it?

4daJKong
  • 1,825
  • 9
  • 21

1 Answers1

2
char G_str [10];

G_str is not initialized. You simply declare the char array G_str with that statement, but do not initialize a string.

Therefore with doing:

int len_G = strlen(G_str);

you will get Undefined Behavior, since strlen searches for a \0 character of a NUL-terminated string, which obviously isn´t existant in G_str.


Change:

char G_str [10];

to at least:

char G_str [10] = "";

or instead:

char G_str[10];
G_str[0] = 0;

to initialize an empty string.

If you want to have the length of the array of G_str in len_G you should not use strlen since it only counts characters until it finds the terminating \0 character of a string, leaving the \0 and the rest of the array (if further char elements after the \0 remain) off the count. Instead you should use the sizeof operator:

int len_G = sizeof(G_str);

to get the capacity of the entired array G_str.