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

int main (int argc, string argv[])
    //checks if argc is 2
    if (argc != 2)
        return 1;

    string k = argv[1];
    string p = GetString();

    for (int i = 0, p_strlen = strlen(p); i < p_strlen; )
        for (int j = 0, k_strlen = strlen(k); j < p_strlen; j++, i++)
            int num_k_array = j % k_strlen;
            int vigenere = k[num_k_array];   

            if (isalpha(p[i]), isupper(p[i]))
                int vigenere_key = vigenere - 65;
                int letter = p[i] - 65;
                int result = ((letter + vigenere_key) % 26) + 65;
                printf("%c", result);

            else if (isalpha(p[i]), islower(p[i]))
                int vigenere_key = vigenere - 97;
                int letter = p[i] - 97;
                int result = ((letter + vigenere_key) % 26) + 97;
                printf("%c", result);
                printf("%c", p[i]);
    return 0;
  • This "I get “/opt/sandbox50/bin/run.sh: line 31: 304…” " is not enough info. I believe if you open the sandbox link, and inspect the failed test it will display more info. Commented Oct 21, 2016 at 14:21
  • puu.sh/rQDr8/6759b586e6.png
    – Cristian
    Commented Oct 21, 2016 at 14:40

1 Answer 1


I compiled your code fine. I ran it like this:

~/workspace/help/pset2/vigenere/Cristian $ ./vigenere aaaa
abcd efgh ijklmnop
abcd efgh ijklmnopSegmentation fault

I ran it again with gdb to see what was happening every step of the way. It all goes smoothly until the inner loop makes i reach p_strlen. Why? Because at that point j is behind if there are any special characters.

In the example run above

p_strlen = 18


i = 18

j is not:

j = 15

Because you are comparing against j on line 20 the loop keeps going. i gets incremented to 19 and you try to access memory you should not access. Therefore, you get a Segmentation Fault.

I suggest you compare against i on line 20 instead of j.

Your approach is very interesting. I had prejudice against your code as soon as I saw a loop inside of a loop for this program. But when I saw that you don't increment in the outer loop, I started to like it more and more. It is always amusing to see how many unique solutions can a problem have.

Awesome code!

  • I wonder however if doing it like this is good design though.
    – Cristian
    Commented Oct 21, 2016 at 16:56
  • It works! It can be improved, but I've rarely seen not improvable code in CS50 students. First, because you are learning. Second, because CS50 is really hard. I love to see all the different approaches to the psets! It is not about how good your code is. It is about how does your mind work. Commented Oct 21, 2016 at 18:11

You must log in to answer this question.

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