c++ 为什么警告“使用未初始化的内存'*unique_counts'"?如何修复?

pod7payv  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(200)

我正在努力解决问题:使用MPI Scatter函数查找二维整数数组的所有唯一元素。如何修复?

Severity    Code    Description Project File    Line    Suppression State   Detail Description
Warning C6001   Using uninitialized memory '*unique_counts'.    ConsoleApplication15    C:\Users\netd3en\source\repos\ConsoleApplication15\ConsoleApplication15\ConsoleApplication15.cpp    29
#include <iostream>
#include <unordered_set>
#include <mpi.h>

int main(int argc, char* argv[]) {
    int size, rank;
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    int arr[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

    int* local_arr = new int[3];
    MPI_Scatter(arr, 3, MPI_INT, local_arr, 3, MPI_INT, 0, MPI_COMM_WORLD);

    std::unordered_set<int> unique_elements;
    for (int i = 0; i < 3; i++) {
        unique_elements.insert(local_arr[i]);
    }

    int* unique_counts = new int[size];
    int local_unique_count = unique_elements.size();
    MPI_Gather(&local_unique_count, 1, MPI_INT, unique_counts, 1, MPI_INT, 0, MPI_COMM_WORLD);

    if (rank == 0) {
        std::unordered_set<int> all_unique_elements;
        int offset = 0;
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < unique_counts[i]; j++) {
                all_unique_elements.insert(local_arr[offset + j]);
            }
            offset += unique_counts[i];
        }

        std::cout << "Unique elements:";
        for (auto it = all_unique_elements.begin(); it != all_unique_elements.end(); it++) {
            std::cout << " " << *it;
        }
        std::cout << std::endl;
    }

    MPI_Finalize();

    return 0;
}
w1jd8yoj

w1jd8yoj1#

你不初始化unique_counts指向的已分配int数组,MPI_Gather可能会失败(你不检查返回值),并保持数组元素不变。

int* unique_counts = new int[size]{};
                                  ^^

不要忘记delete[] unique_counts;

相关问题