0

The following piece of code I've written for pset2/caesar produces a "segmentation error" when there is a lack of key (when no command-line argument is provided). I don't know which line or block of code is producing that error. Please help me out.

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

int key(string input);

int main(int argc, string argv[])
{
    int l = strlen(argv[1]);
    int error = 0;
    int p = 0;

    // if (argc < 2)
    // {
    //     printf("Usage: ./caesar key\n");
    //     return 1;
    // }

    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

    else
    {
    // if (argc == 2)
    // {
        for (int i = 0; i < l; i++)
        {
            int k = argv[1][i];
            if (k > 57 || k < 48)
            {
                error++;
            }

        }
        if (error == 0)
        {
            int k = key(argv[1]) % 26;
            string message = get_string("plaintext:  ");
            printf("ciphertext: ");

            for (int i = 0, n = strlen(message); i < n; i++)
            {
                if (message[i] >= 'a' && message[i] <= 'z')
                {
                    p = (k % 26) + (int) message[i];
                    if (p > 122)
                    {
                        p -= 26;
                    }
                    printf("%c", p);
                }

                else if (message[i] >= 'A' && message[i] <= 'Z')
                {
                    p = (k % 26) + (int) message[i];
                    if (p > 90)
                    {
                        p -= 26;
                    }
                    printf("%c", p);
                }

                else
                {
                    printf("%c", message[i]);
                }
            }

            printf("\n");
        }

        else
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
    //}
    }
    // else
    // {
    //     printf("Usage: ./caesar key\n");
    //     return 1;
    // }

}

int key(string input)
{
    int d = strlen(input);
    int tot = 0;
    for (int i = 0; i < d; i++)
    {
        tot += ((int) input[i] - 48) * pow(10, d - i - 1);
    }
    return tot;
}
0

The program is trying to use argv[1] here int l = strlen(argv[1]); before it knows whether argv[1] exists (if (argc != 2)).

1
  • Thanks a lot!! I finally can submit this problem set :) Dec 9 '20 at 15:38

You must log in to answer this question.

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