0

My program compiles and produces the required ciphertext in caesar problem but when the input has too many characters, I get a segmentation fault after a specific number of ciphertext characters are printed. The number of characters printed before seg fault increases if I reduce the number of variables. For the various inputs that check50 checks, only "world, say hello!" gets the seg fault due to a high number of characters. How so I go about fixing this issue before I submit?

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

int main(int argc, string argv[])
{
    string s = argv[1];
    int q = 0;
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
    }
    else
    {
            for (int i = 0; i < strlen(s); i++)
            {
                if ((int) s[i] < 48 || (int) s[i] > 57)
                {
                    q = 10;
                }
                else
                {
                    q = 1;                    
                }
            }
        if (q == 10)
        {
            printf("Usage: ./caesar key\n");    
        }
        else
        {
            string input = get_string("plaintext: ");
            int key = atoi(s);
            int cypher[strlen(s)];
            printf("ciphertext: ");
            for (int i = 0; i < strlen(input); i++)
            {
                if (((int) input[i] > 64) && ((int) input[i] < 91))
                {
                    cypher[i] = ((((int) input[i] - 64) + (key % 26)) % 26 + 64);
                }
                else if (((int) input[i] > 96) && ((int) input[i] < 123))
                {
                    cypher[i] = ((((int) input[i] - 96) + (key % 26)) % 26 + 96);
                }
                else
                {
                    cypher[i] = (int) input[i];
                }
                printf("%c", (char) cypher[i]);
            }
            printf("\n");
        }
    }
}
0

I wonder what is the length of the variable s in your program? If you want the ciphertext to fit in cypher[i] I would do something like:

int cypher[strlen (input) + 1];

You must log in to answer this question.

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