michael
michael

Reputation: 23

Checking Command Line arguments for error in C

I'm trying to check argument count, which should return 1 if there is no argument or more than 2 arguments in command line:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(int argc, char *argv[])
{
    char *key = argv[1]; //taking the key from CL    
    int n = strlen(key); //length of CL arg string    
    
    if (argc != 2) //checks the amount of CL args
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }

    for (int i = 0; i < n; i++) //validating the key array
    {
        if (n != 26)
        {
            printf("Key must contain 26 characters.\n");
            return 1;
        }
        else if (!isalpha(key[i]))
        {
            printf("Key must contain only alphabetic character.\n");
            return 1;
        }
        for (int j = i + 1; j < n; j++)
        {
            if (key[i] == key[j])
            {
                printf("Key must not contain repeated characters.\n");
                return 1;
            }
        }                
    }
}

When i'm running without an argument it throws an error:

runtime error: null pointer passed as argument 1, which is declared to never be null Segmentation fault (core dumped).

If i'm commenting key validating part, it runs. I'm new in C programming and googled it a lot. Please, help me figure out why?

Upvotes: 1

Views: 1427

Answers (1)

Aplet123
Aplet123

Reputation: 35560

You first access argv[1], which may not exist, then you check argc to see if it exists. This is the wrong order. First check argc, then access argv[1]:

int main(int argc, char *argv[])
{
    if (argc != 2) //checks the amount of CL args
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }

    char *key = argv[1]; //taking the key from CL    
    int n = strlen(key); //length of CL arg string    
    
    // remaining code...

Upvotes: 2

Related Questions