0

I am trying to create a vigenere cipher and I am getting a segmentation fault. I am fairly new, and it would be highly appreciated if someone could help. Thank you in advance.

// Mukul Patel February 26, 2014
int my_key(string key)
{
    int key_length = 0;
    while (key[key_length] != '\0')
        key_length++;

    return key_length;
}

int main(int argc, string argv[])
{
    if (argc != 2){ 
        printf("Please only enter two arguments which are non-numerical\n");
        return 1;
    }

    string key = argv[1];

    string plaintext = GetString();

    for (int i = 0, length = strlen(plaintext); i < length; i++){
        for (int j = 0, n = my_key(argv[i]); j < n; j++){
            if(isupper(plaintext[i]))
                plaintext[i] = ((((plaintext[i] - 'A') + (key[j % strlen(key)] - 'A')) % ALPHABET) + 'A');
            else if(islower(plaintext[i]))
                plaintext[i] = ((((plaintext[i] - 'a') + (key[j % strlen(key)] - 'a')) % ALPHABET) + 'a');
            else
                plaintext[i] = plaintext[i];

            printf("%c", plaintext[i]);
        }
    }    
    printf("\n");

return 0;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
itzmurd4
  • 663
  • 10
  • 25
  • key: abcdabcd plaintext: this is a test! – itzmurd4 Feb 26 '14 at 21:02
  • 3
    What is a `string` type? I haven't heard of one in C. What is `GetString`? Do you #include any files? Which are they? Are they standard ones? If not, what is their content? *In short: Please provide a ["short, self contained, compilable example"](http://www.sscce.org/).* – ArjunShankar Feb 26 '14 at 21:02
  • sorry, its part of a library for a class. Just a training wheel for I guess, scanf – itzmurd4 Feb 26 '14 at 21:04

1 Answers1

0

This: my_key(argv[i]) in line for (int j = 0, n = my_key(argv[i]); j < n; j++).

You accept only two arguments. So size of argv[] is 2. If i>=2, index of array goes out of bounds. So it may give segmentation fault error.

HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33