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

C++运行报[1] 41387 illegal hardware instruction错误如何解决

问题分析与修复方案

存在的4个核心错误

    1. 缺少必要头文件:使用std::cout/std::cin需要引入<iostream>头文件,使用std::string需要引入<string>头文件,缺少头文件属于非标准写法,会导致部分编译器编译失败或运行异常。
    1. 字符串越界访问:C++ std::string 的下标从0开始计数,最后一个有效字符的下标是长度-1。你在isFeminine函数中直接用countryName[countryName.length()]访问,已经超出了字符串的合法内存范围,属于未定义行为,是触发硬件报错的核心原因。
    1. 函数无有效返回值:masculineExceptions 声明为返回std::string类型,但遍历完异常列表调用isFeminine后,没有加return语句把结果返回,调用方会拿到非法的垃圾值,也会触发未定义行为。
    1. 异常列表遍历不完整:你定义的特殊阳性国家数组有6个元素,但for循环只判断到i<5,最后一个zimbabwe永远不会被匹配到,属于逻辑漏洞。

修正后的完整代码

#include <iostream>
#include <string>
using namespace std;

string isFeminine(string countryName)
{
    // 修正下标:取最后一个字符用 length()-1
    if (countryName[countryName.length() - 1] == 'e')
    {
        string country = "la " + countryName;
        cout << country << endl;
        return country;
    }
    else
    {
        string country = "le " + countryName;
        cout << country << endl;
        return country;
    }
}

string masculineExceptions(string countryName)
{
    string masculineExceptions[] = {"belize", "cambodge", "mexique", "mozambique", "zaire", "zimbabwe"};
    // 修正循环上限:6个元素对应i从0到5,判断条件改为i<6
    for (int i = 0; i < 6; i++)
    {
        if (countryName == masculineExceptions[i])
        {
            string country = "le " + masculineExceptions[i];
            cout << country << endl;
            return country;
        }
    }
    // 补全return语句,返回isFeminine的执行结果
    return isFeminine(countryName);
}

int main()
{
    cout << "Enter Country Name: ";
    string countryName;
    cin >> countryName;
    masculineExceptions(countryName);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:39:04