Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

c - 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
");
        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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...