In my MPI code in C, i'm receiving a word from each of my slave processes. I want to add all these words to an char array in master side (part of code below). I can print these words but not collect them into a single char array. (I consider max word length as 10, and number of slave's as slavenumber)

char* word = (char*)malloc(sizeof(char)*10);
char words[slavenumber*10];
for (int p = 0; p<slavenumber; p++){
    MPI_Recv(word, 10, MPI_CHAR, p, 0,MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    printf("Word: %s\n", word); //it works fine
    words[p*10] = *word; //This does not work, i think there is a problem here.
}
printf(words); //This does not work correctly, it gives something like: ��>;&�>W�

Can anybody help me on this?

1 Answers

0
datenwolf On

Let's break it down line by line

// allocate a buffer large enough to hold 10 elements of type `char`
char* word = (char*)malloc(sizeof(char)*10);

// define a variable-length-array large enough to
// hold 10*slavenumber elements of `char`
char words[slavenumber*10];

for (int p = 0; p<slavenumber; p++){
    // dereference `word` which is exactly the same as writing
    // `word[0]` assigning it to `words[p*10]`
    words[p*10] = *word;

    // words[p*10+1] to words[p*10+9] are unchanged,
    // i.e. uninitialized
}

// printing from an array. For this to work properly all
// accessed elements must be initialized and the buffer
// terminated by a null byte. You have neither
printf(words);

Because you left elements uninitialized and didn't null terminate, you're invoking undefined behavior. Be happy that you didn't get demons crawl out of your nose.

In seriousness though, in C you can copy strings by mere assignment. Your usage case calls for strncpy.

for (int p = 0; p<slavenumber; p++){
    strncpy(&words[p*10], word, 10);
}