首页 > 解决方案 > C++ MPI Iprobe unitialized local variable 'buf' used

问题描述

I'm new to C++ and MPI. Got the task and read a lot. I`m still confident that I wrote everything correctly, but still unable to execute without any errors. My code:

#include <iostream>
#include <mpi.h>

using namespace std;

int main() {
int myid, numprocs, **buf, source, i; 
    int message[3] = { 0, 1, 2 };
    int myrank, data = 2002, count, TAG = 0;
    MPI_Status status; 
    MPI_Init(NULL, NULL); 
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);

    if (myrank == 0) {
        MPI_Send(&data, 1, MPI_INT, 2, TAG, MPI_COMM_WORLD);
    }
    else if (myrank == 1) {
        MPI_Send(&message, 3, MPI_INT, 2, TAG, MPI_COMM_WORLD);
    }
    else {
        MPI_Probe(MPI_ANY_SOURCE, TAG, MPI_COMM_WORLD, &status);
        source = status.MPI_SOURCE; 
        MPI_Get_count(&status, MPI_INT, &count);

        for (i = 0; i < count; i++) {
            //buf[i] = new int[count * sizeof(int)];
             buf[i] = (int *)malloc(count * sizeof(int));
        } 
        MPI_Recv(&buf[0], count, MPI_INT, source, TAG, MPI_COMM_WORLD, &status);
        for (i = 0; i < count; i++) {
            printf("received: %d\n", buf[i]);
        }
    }
    MPI_Finalize();

    return 0;
}

Errors:

Error   C4700   uninitialized local variable 'buf' used

I don't get why it wants it to be initialized. I gave the memory space and just want to fill it further. It seems I don`t unserstand some C++ simple operation or smth. Initializing something like

int **buf = nullptr;

Also tried:

buf[i] = new int[count * sizeof(int)];

didn`t make any difference. Please give me a hint.

标签: c++mallocmpinew-operator

解决方案


好吧,我认为您需要检查计数值。

示例(提示(?))

count = 0;

再试一次


推荐阅读