0

I just finished my code for hail Caesar but for some reason when I don't give it a key, instead of exiting the programme and printing it gives me a segmentation error. Also It fails check 50 saying that I encrypt the text wrong but it works correct except the issue with the no key situation.

Any help would be much appreciated, thanks in advance.

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

int lower(int input);
int upper(int input);

int key;

int main(int argc, string argv[])
{

key = atoi(argv[1]);

if (argc != 2)
{
    printf("./caesar key (the key must be an int)");
    return 1;
}

else

{
    printf("Your Key is:%i\nPlease provide me with the plain text my kind sir!:", key);
    string plain = GetString();

    for (int i = 0, n = strlen(plain); i < n; i++)
    {
        if (isalpha(plain[i]))
        {
            if (isupper(plain[i]))
            {
                printf("%c", upper(plain[i]));
            }
            if (islower(plain[i]))
            {
                printf("%c", lower(plain[i]));
            } 
        }
        else
        {
            printf("%c", plain[i]);
        } 
    }
}
}

int upper(int input)
{
int i = input - 65 + key;
i = i % 26;
int k = i + 65;
return k;
}

int lower(int input)
{
int i = input - 97 + key;
i = i % 26;
int k = i + 97;
return k;
}

1 Answer 1

1

When main() is called with no key argument, argc is 1 and argv contains only one element, "./ceasar". The problem occurs in key = atoi(argv[1]); which attempts to read the non-existent second index of argv, causing the error. Try moving key = atoi(argv[1]); below if (argc != 2) {...}, so the program will exit before trying to read a garbage value.

7
  • Thank you, also a question about the scope when I move it. As I initialized it as a global variable if I change its value within the nested if blocks will it retain that value everywhere? Like in my functions?
    – Code
    Commented Nov 13, 2014 at 23:17
  • Yes, every method will reference the same memory location when accessing a global variable.
    – Paul
    Commented Nov 14, 2014 at 21:46
  • Brilliant, but what if I decalred the varioa
    – Code
    Commented Nov 14, 2014 at 23:46
  • Brilliant, but say if I declared the variable key in int main, and I made a line of code that changed its value in one of my loops. Will it change the value of key or would it make a copy local to the loop and assign that the value?
    – Code
    Commented Nov 14, 2014 at 23:48
  • If it were declared in main, it would become a local variable and you could not access it in the methods lower() and upper().
    – Paul
    Commented Nov 15, 2014 at 23:33

You must log in to answer this question.

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