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

代码运行触发段错误(Core Dump):电话号码转单词功能异常排查

问题分析与解决

你的代码触发段错误的核心原因是数组长度计算错误,导致递归时越界访问了数组内存:

  • 在main函数中,int size_of_num = sizeof(numbers); 得到的是数组numbers占用的总字节数(对于包含3个int元素的数组,通常是12字节),而非数组的实际元素个数。
  • 递归过程中,index会持续递增到12,远超numbers仅有的3个元素,此时访问num[index]会读取不属于数组的内存区域,直接触发段错误。

修正后的代码

#include <iostream>
#include <string>
#include <vector>

using namespace std;

void converter(vector<char> keypad[], int num[], int index, string result, int size_of_num){
    if(index == size_of_num){
        cout << result << " ";
        return;
    }

    int digit = num[index];
    int size_of_keypad = keypad[digit].size();

    for(int i=0; i < size_of_keypad; i++){
        converter(keypad, num, index + 1, result + keypad[digit][i], size_of_num);
    }
}

int main(){
    vector<char> keypad[] = {
        {},{},{'a','b','c'},
        {'d','e','f'},
        {'g','h','i'},
        {'j','k','l'},
        {'m','n','o'},
        {'p','q','r','s'},
        {'t','u','v'},
        {'w','x','y','z'}
    };

    int numbers[] = {2,3,4};
    // 正确计算数组元素个数:总字节数除以单个元素字节数
    int size_of_num = sizeof(numbers) / sizeof(numbers[0]);
    
    converter(keypad, numbers, 0, "", size_of_num );

    return 0;
}

额外优化建议

  • string ("")可直接简化为"",代码更简洁且效果一致。
  • 可为递归函数的输入参数添加const修饰(如const int num[]、const string& result),避免不必要的拷贝,提升运行效率(此优化不影响段错误修复)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:50:17