c - 分段错误和 isalpha
问题描述
我想在使用命令行参数时澄清我对分段错误的理解,isalpha()
但这种特殊情况让我更加困惑。因此,我按照此SO 答案的建议声明argv[1]
了 achar *
作为解决方法。
但是,Segmentation Fault
如果我使用少于 2 个命令行参数,仍然会发生,并且isalpha()
在 if 3rd 条件中被忽略
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> //atoi is here
int main(int argc, char* argv[]){
char *input = argv[1];
// Error handling
if ((argc > 2) || (argc < 1) || (isalpha(input[1])))
{
printf("Unwanted input\n");
return 1;
}
return 0;
}
为什么不使用命令行参数时会出现未定义的行为,为什么会isalpha()
被忽略而不是给我一个段错误?
感谢您花时间阅读这篇文章
解决方案
当您执行没有 args 的程序时,argc
is 1
(因为程序名称本身也算作 arg),并且argv[1]
is NULL
。
(argc > 2) || (argc < 1) // Considers argc == 1 and argc == 2 acceptable
应该
(argc > 2) || (argc < 2) // Only considers argc == 2 acceptable
要不就
argc != 2
推荐阅读
- oauth - WSO2 Oauth 实施
- google-bigquery - BigQuery - Adwords 数据传输 - AccountStats 与 AccountBasicStats
- enums - 如何有条件地检查枚举是否是一个变体?
- three.js - 如何为球体创建简单的垂直反弹动画
- c - 在 c 中刷新缓冲区
- mysql - 在 SQL 中根据日期组织数据
- c++ - 转换移动构造函数的模板特化的 std::variant
- javascript - 如何在用户单击按钮后将列表动态添加到预先存在的列表集中
- javascript - Angular 正则表达式验证器无法正常工作
- jetty - 在 Windows 中使用 logback 在 ${jetty.home} 之外启动码头