【问题标题】:How to deal with segmentation fault [duplicate]如何处理分段错误[重复]
【发布时间】:2021-05-20 06:36:40
【问题描述】:

我正在尝试使用 for 循环逐个更改字符串的字符,并且在real_A[i]=ciphertext[i]; 中发生分段错误,这是使用密文更改 real_A 字符串的字符的代码。 这是我的代码:

string substitution(string plaintext, string ciphertext)
{
    string real_A="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string real_a="abcdefghijklmnopqrstuvwxyz";
    
    
    //change alphabets to ciphertext
    for (int i=0,n=strlen(ciphertext);i<n;i++)
    {
        if (isupper(ciphertext[i]))
        {
           real_A[i]=ciphertext[i];
           real_a[i]=real_A[i+32];
        }
        else if (islower(ciphertext[i]))
        {
           real_a[i]=ciphertext[i];
           real_A[i]=ciphertext[i-32];
     }
    for (int i=0,n=strlen(plaintext);i<n;i++)
    {
        if (isupper(plaintext[i]))
        {   
           //get the ascii num
           int letter=plaintext[i]-65;
           
           plaintext[i]=real_A[letter];
        }
        else if (islower(ciphertext[i]))
        {
           int letter=plaintext[i]-97;
           plaintext[i]=real_a[letter];
        }
    }
    
    return plaintext;
      
}

我该如何处理这个错误?我试图将 string real_A="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 更改为 string real_A[26];,但它给我带来了更多错误。

【问题讨论】:

  • 您似乎正在尝试更改字符串文字。任何更改字符串文字的尝试都会导致未定义的行为。
  • 在任何情况下,该函数至少没有任何意义,因为尽管它的返回类型不是 void 并且函数中未使用参数明文,但它什么也不返回。:)
  • 请提供minimal reproducible example。至少可以更好地检查这里的关键字string 指的是什么。
  • 快速解决方法是将string real_A="..."; 替换为char real_A[]="...";real_a 也是如此。这会将real_Areal_a 定义为可以修改的char 数组。
  • @Damien typedef char *string 是一个被辱骂和误导的 CS50 可憎之物,以混淆太多 C 新手而闻名。

标签: c++ arrays string segmentation-fault cs50


【解决方案1】:

由于您使用的是string,我假设您使用的是 C++ 而不是 C?!

您的代码产生了分段错误,因为您在这里使用了超出范围的索引:

real_a[i]=real_A[i+32];

由于 i 在 0 到 ciphertext 参数的长度范围内,并且您的 real_A 字符串的大小仅为 26,因此索引将始终超出范围。

您在这里遇到了类似的问题:

real_A[i]=ciphertext[i-32];

注意:假设这是 C++ 代码,并且您使用的 stringstd::stringreal_areal_A 是用文字初始化的字符串,它们不是字符串文字。在这种情况下,如果您的索引有效,您就可以写入 std::string 索引。例如,这是正确的 C++ 代码:

std::string a = "Test";
a[0] = 'B';
std::cout << a << std::endl;

【讨论】:

  • 感谢您指出该错误,但实际上分段错误是因为stackoverflow.com/questions/164194/…。抱歉,它不是 C++,而是 C。我正在使用一个简化初学者的库,这就是我使用 string 分配字符串文字的原因。
猜你喜欢
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
  • 2011-10-01
相关资源
最近更新 更多