You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

输入数据后触发zsh: segmentation fault,求C++代码修复方案

C++代码段错误排查与修复

问题重现

输入第一个整数(如10)后立即触发zsh: segmentation fault错误,代码预期功能为读取整数存入vector并计算总和。

错误原因分析

  1. isdigit函数误用
    isdigit用于判断单个字符的ASCII值是否为数字字符(如'0'-'9'),但你传入的是int类型的输入值(比如输入10时,temp是整数10,对应ASCII码为控制字符,并非数字字符)。这导致输入有效整数时循环条件不成立,vector始终为空;输入非数字时,cin读取失败会让temp值不确定,引发未定义行为。

  2. sum函数越界访问
    vector::capacity()返回的是vector当前分配的内存容量,而非实际存储的元素数量。空vector的capacity可能大于0,但此时访问vec[i]属于越界访问,直接触发段错误。正确应该使用vector::size()获取实际元素数。

  3. sum变量未初始化
    sum函数中的float sum;未初始化就直接累加,会导致计算结果为随机垃圾值,属于未定义行为。

修复后的代码

#include <iostream>
#include <vector>
#include <cctype>
#include <limits>

using namespace std;

vector<int> get_data(){
    vector<int> v;
    int temp;
    
    // 循环读取整数,直到cin读取失败(输入非整数)
    while(cin >> temp){
        v.push_back(temp);
    }
    
    // 清除cin错误状态,忽略缓冲区剩余无效字符
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    
    return v;
}

int sum (const vector<int>& vec){ // 用const引用避免不必要拷贝
    float sum = 0.0f; // 初始化sum变量
    // 遍历实际存储的元素
    for(size_t i = 0; i < vec.size(); i++){
        sum += vec[i];
    }
    return static_cast<int>(sum);
}

int main(){
    vector<int> data_main;

    cout << "\nPlease enter your data." << endl;
    cout << "You can enter non-integer to notify the end of your data." << endl;
    
    data_main = get_data();

    cout << "The sum of the vector elements is " << sum(data_main) << endl;

    return 0;
}

修复说明

  • 替换输入判断逻辑:直接用cin >> temp作为循环条件,输入非整数时cin进入失败状态,循环终止,这是判断整数输入的正确方式。
  • 修复sum函数:使用vec.size()遍历实际元素,初始化sum变量,同时用const引用传递vector提升效率。
  • 添加cin错误处理:读取失败后清除错误状态并忽略缓冲区剩余字符,避免后续IO操作异常。

内容的提问来源于stack exchange,提问作者Andy Hernandez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 13:58:09