分段错误(核心已转储)- C++ 错误

Segmentation fault (core dumped) - C++ Error

我正在尝试编写一个简单的向量加法代码,但出现此错误。我不知道那是什么。我在 Ubuntu 18.04.

中使用 VS Code
int main(){
    std::vector<int> vect1 = {1,2,3,4,5};
    std::vector<int> vect2 = {6,7,8,9,10};
    std::vector<int> vectsum;

    for (int i = 0; i < vect1.size(); i++){
        std::cout << vect1[i] << " ";
    }

    std::cout << std::endl;

    for (int j = 0; j < vect2.size(); j++){
        std::cout << vect2[j] << " ";
    }

    for(int i = 0; i < vect1.size(); i++){
        vectsum[i] = vect1[i] + vect2[i];
    }

    for (int i = 0; i < vectsum.size(); i++){
        std::cout << vectsum[i] << " ";
    }
    return 0;
}

输出:

1 2 3 4 5 
Segmentation fault (core dumped)

您还没有为 vectsum 分配任何内存(所以当您为其中一个元素赋值时,您遇到了 NULL 指针)

std::vector<int> vectsum(5);

在行 vectsum[i] = vect1[i] + vect2[i]; 中,您没有通过为容器添加下标来向 vectsum 添加元素。您正在尝试访问未分配的内存区域。

一个简单的解决方案可以是以下形式:

for(int i = 0; i < vect1.size(); i++){
    // Allocate memory as needed
    vectsum.push_back(vect1[i] + vect2[i]);
}

使用下标时还应考虑以下警告:

warning: comparison of integer expressions of different signedness: 
‘int’ and ‘std::vector<int>::size_type’ {aka ‘long unsigned int’}

告诉你不要混合使用有符号和无符号类型。