CS50 Week2 Caesar程序无命令行参数时触发段错误求助
问题:CS50 Caesar程序无参数运行触发段错误
我编写了CS50 Week 2 Caesar程序的初步代码,用于检查命令行参数是否为0-9的数字,无参数时要求用户输入正确格式。目前程序在输入非数字或多个参数时能正常输出错误信息,但无参数执行时会触发“Segmentation fault (core dumped)”,而非自定义的错误提示。
尝试的代码
#include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> bool only_int(string inputkey); int check(string inputkey); int main(int argc , string argv[]) { bool check = only_int(argv[1]); if(argc == 2) { if(check == true) { string plaintext = get_string("plaintext : "); return 0; } else { printf("Usage: ./caesar key\n"); return 1; } } else if((argc != 2) || (argv[1] == NULL)) { printf("Usage: ./caesar key\n"); return 1; } } // 检查输入是否仅包含整数的函数 bool only_int(string inputkey) { int y = check(inputkey); if(y > 0) { return true; } else { return false; } } int check(string inputkey) { int result = 0; for(int i = 0 , l = strlen(inputkey) ; i < l ; i++) { int x = isdigit(inputkey[i]); if (x > 0) { result++; } } return result; }
预期输出
$ ./caesar Usage: ./caesar key $ ./caesar HELLO Usage: ./caesar key $ ./caesar 1 2 3 Usage: ./caesar key $ ./caesar 13 plaintext:
实际输出
$ ./caesar HELLO Usage: ./caesar key $ ./caesar 1 2 3 Usage: ./caesar key $ ./caesar Segmentation fault (core dumped) $ ./caesar 13 plaintext:
问题根源
段错误的直接原因是在检查argc是否合法之前,就调用了only_int(argv[1]):
- 当无参数运行时,
argc=1,argv[1]是NULL空指针; - 把
NULL传给check函数后,strlen(NULL)会尝试访问非法内存,直接触发段错误。
另外,原代码的only_int逻辑存在缺陷:只要输入中有一个数字字符就返回true,但实际上需要所有字符都是数字才符合要求。
修复方案
调整代码逻辑顺序,先判断参数数量是否合法,再检查参数内容;同时修正参数合法性判断逻辑:
修复后的代码
#include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> bool only_digits(string inputkey); int main(int argc , string argv[]) { // 先处理参数数量不对的情况 if(argc != 2) { printf("Usage: ./caesar key\n"); return 1; } // 参数数量合法时,再检查是否全为数字 if(only_digits(argv[1])) { string plaintext = get_string("plaintext : "); return 0; } else { printf("Usage: ./caesar key\n"); return 1; } } // 检查输入是否全为数字字符 bool only_digits(string inputkey) { for(int i = 0 , l = strlen(inputkey) ; i < l ; i++) { // 只要有一个字符不是数字,直接返回false if (!isdigit(inputkey[i])) { return false; } } // 所有字符都是数字,返回true return true; }
验证结果
修复后所有场景均符合预期:
- 无参数运行:输出
Usage: ./caesar key - 非数字参数:输出错误提示
- 多参数:输出错误提示
- 合法数字参数:正常提示输入明文
内容的提问来源于stack exchange,提问作者Manasvi Sharma
相关产品推荐
相关产品推荐

