This code is supposed to work as a vigenere cipher. When run, however, no matter what input you put in, it segmentation faults. I'm writing this for the online CS50 course on edx. Isn't strncpy
supposed to stop segmentation faults from happening if I tell it to copy over the right amount of characters?
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[]) {
int result;
if (argc != 2) {
printf("Shame on you!\n");
return 1;
}
string key = argv[1];
string text = GetString();
string cpy_key = NULL;
//strncpy(cpy_key, key, strlen(key));
for (int i = 0, n = strlen(text); i < n; i++) {
strcat(cpy_key, key);
}
cpy_key[strlen(text)] = '\0';
// Main loop starts here
for (int i = 0, n = strlen(text); i < n; i++) {
result = text[i] + cpy_key[i];
if (isupper(text[i]) && (result > 'Z')) {
result = result - 26;
}
if (islower(text[i]) && (result > 'z')) {
result = result - 26;
}
if (isalpha(text[i])) {
printf("%c", result);
} else {
printf("%c", text[i]);
}
}
printf("\n");
return 0;
}