0

Rewriting my question, because I've finally figured out which function was returning segfault, but I still don't understand why.

The first part of my code:

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

int main (int argc, string argv[]) 

{

    //Checks that the key exists.
    if (argc!=2)
    {
        printf("Please enter a valid numerical key after program name.\n");
        return 1;
    }

    //Checks that the key is a non-negative number.
    else if (argv[1] < 0 || isdigit(argv[1])
    {
        printf("Please enter a non-negative numerical key after program name.\n");
        return 1;
    }
}

I've figured out that it's the isdigit function that keeps returning segfault, and removing it results in the program working perfectly. My question is: why? Must I turn argv[1] into an int before checking that it's a digit or..?

1
  • There's more to the code, obviously - Check50 says it exists, compiles, and successfully rejects an invalid key. Plus, there is an 'else' to the first two ifs at the end that I didn't include in this code. I'm pretty sure it's just this bit that is weird.
    – cursue
    Aug 24 '14 at 20:46
4

Doesn't isdigit only work on chars, rather than argv[1] which is a string?

2
  • Oh! Thank you! I see it now. It hadn't even crossed my mind... That was quite stupid of me.
    – cursue
    Aug 25 '14 at 22:03
  • 1
    Glad to help. Woohoo my first answer! Aug 25 '14 at 23:06
2

If you don't provide a key, you will segfault when you try to call atoi(argv[1]). Are you verifying that argv[1] exists? If not, you must.

1
  • Yes, it initially checks that argv[] contains no more or less than 2 items: while (argc!=2) { printf("Please enter a valid numerical key after './caesar'.\n"); return 1; }
    – cursue
    Aug 25 '14 at 8:35
1

Looks like you also forgot to close a parenthesis at the end of:

else if (argv[1] < 0 || isdigit(argv[1])

You must log in to answer this question.

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