0

I keep getting 'Segmentation fault' every time I run the code(mentioned below). The code is compiling just fine. It's asking for input and is returning required message when the command line argument is less than 26 or if anything other than an alphabet is present. I don't know where exactly I'm going wrong.

If you know what to do, could you please help me out here?

Thank you!

Code:

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

bool valid(string text);

int main (int argc, string argv[])
{
    if(argc != 2)
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }
    if( !valid(argv[1]))
    {
        printf("Key must contain 26 characters.\n");
        return 1;
    }
    string text = get_string("Plaintext: ");
    printf("Ciphertext: ");
    char citext[strlen(text)];
    for (int i = 0; i < strlen(text); i++)
    {
        if(isupper(text))
        {
            citext[i] = toupper(argv[1][i]);
            printf("%c", citext[i]);
        }
        else if(islower(text))
        {
            citext[i] = tolower(argv[1][i]);
            printf("%c", citext[i]);
        }
        else
        {
            printf("%c", text[i]);
        }
    }
    printf("\n");
}


bool valid(string text)
{
    if(strlen(text) != 26)
    {
        return false;
    }
    for (int i = 0, n = strlen(text); i < n; i++)
    {
        if (!isalpha(text[i]))
        {
            return false;
        }
        for (int j = 0; j < n; j++)
        {
            if(toupper(text[i]) == toupper(text[j]) && i != j)
            {
                printf("Key must not be repeated.\n");
                return false;
            }
        }
    }
    return true;
}
  • Hi. Study the following link. When you can identify the line causing the seg fault, edit the question and let us know which line and what you think might be the problem. Identifying WHERE a seg fault occurs is a critical skill. cs50.stackexchange.com/questions/37065/… I will say this. The problem is a common error and easily fixed. ;-) – Cliff B Jul 4 at 7:10
  • @CliffB THANK YOU SO MUCH!!! I understood my mistake. – gargi Jul 12 at 6:46

You must log in to answer this question.

Browse other questions tagged .