0

I'm trying to print the value of argv[1] to check if the program will run as expected. It compiles fine, but I keep getting 'segmentation fault' when the program runs.

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

int main(int argc, string argv[])
{
//string text;
if (argc != 2)
{
    printf("Usage: ./caesar key\n");
    return 1;
}
else
{
    if (isdigit(argv[1]))// this could be argv[argc - 1]
    {
        printf("%s\n", argv[1]);
        return 0;
    }
    else
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
}
/*text = get_string("Plaintext: ")*/ //plaintext by user
}

2 Answers 2

2

This issue is with this:

isdigit(argv[1])

The isdigit() function (and related functions in the same family) takes a single char as input. The problem here is that argv[1] is a string, not a char. By trying to shove an entire string down isdigit's throat, it chokes and coughs up a seg fault.

You would need to check each char in the string individually. Hint: think two dimensional array.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
-1

It's about

isdigit(argv[1])

like Cliff B says. But the problem here is argv[1] doesn't exist. You're trying to run the program and it's trying reach a RAM part where you program is not allowed because you didn't give any arguments and still wanted the [1] index of argument. And it's tring to reach that part of RAM. Hope this is helpful.

1
  • Not true. If there were no argument, the program would run to completion because it correctly checks the value of argc first. It would detect the lack of a parameter and execute a return statement, thus terminating the program, before even reaching the isdigit() call.
    – Cliff B
    Sep 30, 2020 at 23:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .