【问题标题】:Adding two adjacent elements in a vector giving a segmentation fault for odd numbers (c++)在向量中添加两个相邻元素,给出奇数的分段错误(c++)
【发布时间】:2021-05-27 14:42:25
【问题描述】:

我很想了解为什么我的 C++ 程序会产生分段错误。任务是将元素插入向量中,并将存储在该向量中的相邻元素相加。当向量中有奇数个元素时,就会出现问题。我最终通过将 idx != numbers.size() 更改为 idx

#include <iostream>
#include <vector>

using std::cout;
using std::cin;
using std::endl;
using std::vector;

int main(){
    vector<int> numbers = {1, 2, 3, 4, 5};
    int tmp;

    /*while(cin >> tmp){
        numbers.push_back(tmp);
    }*/

    for(decltype(numbers.size()) idx = 0; idx < numbers.size(); idx+=2){
        if((numbers.size() % 2 != 0) && (idx == numbers.size() - 1)){
            cout << numbers[idx] << endl;
        }
        else{
            cout << numbers[idx] + numbers[idx+1] << " ";
        }
    }

    cout << endl;

    return 0;
}

【问题讨论】:

  • numbers[idx+1]idx + 1 == numbers.size() 时的未定义行为。另外,从不idx == numbers.size() - 1,因为空容器的情况下没有签名。请改用1 + idx == numbers.size()
  • 感谢您的回复!
  • @Bathsheba:这再次表明,a)不要对无符号值进行算术运算,b)非常不幸的是,STL 设计者将他们的 size_type 设置为无符号类型。

标签: c++ for-loop vector null segmentation-fault


【解决方案1】:

“!=”不适用于奇数大小的向量的原因是 idx 从 0 开始,每次前进 2。

所以考虑一下向量大小为 5 的示例。

idx 将具有值 0、2、4、6、8 等等,但 idx 永远不会具有值 5,因为 idx 将始终是偶数。当 idx 足够大以至于 numbers[idx] 不引用可读内存时,这将导致不好的事情,例如分段错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 2022-11-15
    • 2014-08-12
    • 1970-01-01
    • 2021-08-06
    • 2016-04-26
    相关资源
    最近更新 更多