0

I'm currently running into a segmentation fault when I don't put a key in the command line. I'm trying to say that if argc = 1 then "Please type key in command-line." but instead I'm getting the fault. Can anyone help with this please? See my code below. Thanks in advance!

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

//Prototypes
int compute_score(string key);

int main(int argc, string argv[])
{
    //1. Get key (as a command line argument)
    //2. Validate key
    string key = argv[1];
    int alphacheck = compute_score(key);
    
    if (argc == 2 && strlen(key) == 26 && alphacheck == 0)
    {
        printf("Key is valid!\n");
    }
    else if (argc == 1)
    {
        printf("Please type key in command-line.\n");
        return 1;
    }
    //2a. Check the key length
    else if (strlen(key) != 26)
    {
        printf("Please use a key that has 26 characters.\n");
        return 1;
    }
    //2b. check for non-alphabetic characters
    else if (alphacheck != 0)
    {
        printf("Please use a key that contains only characters.\n");
    }
    
    //2c. Check for repeated characters (case-insenstive)
    
    //3. Get plaintext
    string plaintext = get_string("plaintext: ");
    
    //4. Encipher
        //4a. For each alphabetic character, determine what letter it maps to
        //4b. Preserve case
        //4c. Leave non-alphabetic characters as is
    //5. Print ciphertext
    
}
//Function for checking to see if key has non-alphabetic characters
int compute_score(string key)
{
    int sum = 0;
    for (int i = 0; i < strlen(key); i++)
    {
        if (isalpha(key[i]))
        {
            sum = sum + 0;
        }
        else
        {
            sum = sum + 1;
        }
    }
    return sum;
}

1 Answer 1

3

It's a common mistake. Look at this code (comments removed):

int main(int argc, string argv[])
{
    string key = argv[1];

The first line in main is trying to read argv[1]. If no parameter is given, then argc = 1 and argv[1] doesn't exist. (FYI, argv[0] contains the program name as it was entered when the program was invoked.) Because argv[1] doesn't exist, it throws a seg fault error.

The code needs to check if argc is 2 before it does anything else. If it isn't 2, then the code needs to decide what to do then (like, say, if argc = 0 or something greater than 2?)

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

1
  • Thank you so much for the answer and for being kind!
    – hawki2sl
    Commented Aug 25, 2021 at 21:38

You must log in to answer this question.

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