Search code examples
csegmentation-faultcommand-line-argumentsisalpha

Segmentation Fault and isalpha


I want to clear up my understanding of Segmentation faults while using command-line arguments and isalpha() but this particular situation confused me more. So I declared argv[1] a char * as a way around it as advised by this SO answer.

However, Segmentation Fault still occurs if I used less than 2 command line arguments, and isalpha() is ignored in the if 3rd condition

#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;

}

Why do I get undefined behaviour when not using a command-line argument, and why then does isalpha() get ignored rather than giving me a seg fault?

Thanks for taking the time to read this post


Solution

  • When you execute the program with no args, argc is 1 (cause the program name itself counts as an arg), and argv[1] is NULL.

    (argc > 2) || (argc < 1)   // Considers argc == 1 and argc == 2 acceptable
    

    should be

    (argc > 2) || (argc < 2)    // Only considers argc == 2 acceptable
    

    or just

    argc != 2