【问题标题】:Can anyone tell me why im getting a Segmentation Fault (cs50 substitution)谁能告诉我为什么我得到一个分段错误(cs50替换)
【发布时间】:2020-11-14 22:33:31
【问题描述】:

在我的程序中,我得到了我控制的错误,但是当我试图避免这些预设错误并输入我希望用户输入的内容时,它会返回一个分段错误。

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, string argv[])
{
    string key = argv[1];
    if (argc < 2 || argc > 2)
    {
        printf("Usage: ./substitution key\n");
        exit(1);
    }
    
    if (argc == 2 && strlen(key) < 26)
    {
        printf("Key must contain 26 characters.\n");
        exit(1);
    }
    
    if (strlen(key) > 26)
    {
        printf("Key must contain 26 characters.\n");
        exit(1);
    }
    
    for (int i = 0; i < 26; i++)
    {
        if (isalpha(key) == 0)
        {
            printf("MAKE SURE YOUR KEY ONLY HAS LETTERS\n");
        }
    }
    printf("test");
}

【问题讨论】:

  • 您应该在使用它们之前检查正确数量的命令行参数。这也是错误的:if (isalpha(key) == 0)应该是if (isalpha(key[i]) == 0)。在您已经确定是argc == 2 之后,您不需要检查它,如果您可以计算一次长度并检查它是否为!= 26 以减少重复代码。同样if (argc != 2) 对我来说似乎更清楚。
  • 顺便说一句,gdb 是个好朋友。 g++ -g &lt;filename&gt;.c 然后使用gdb --args ./a.out &lt;arguments&gt;。现在输入r。如果崩溃,bt 进行回溯。当然还要学习其他的东西,比如断点b &lt;line number&gt; 和单步执行n 或单步执行s,这会让你的生活变得非常轻松

标签: c segmentation-fault cs50


【解决方案1】:

@Retired Ninja 很到位。 isalpha on key 导致了分段。下面是稍微优化的代码方式。

#include <stdio.h>
#include "cs50.h"
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./substitution key\n");
        exit(1);
    }
    
    string key = argv[1];
    int keylen = strlen(key);
    
    if (keylen != 26)
    {
        printf("Key must contain 26 characters.\n");
        exit(1);
    } 
    
    for (int i = 0; i < 26; i++)
    {
        unsigned char const c = key[i];
        if (!isalpha(c))
            printf("MAKE SURE YOUR KEY ONLY HAS LETTERS\n");
    }
    printf("test\n");
}

【讨论】:

猜你喜欢
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
相关资源
最近更新 更多