首页 > 解决方案 > 分段错误和 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()被忽略而不是给我一个段错误?

感谢您花时间阅读这篇文章

标签: csegmentation-faultcommand-line-argumentsisalpha

解决方案


当您执行没有 args 的程序时,argcis 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

推荐阅读