此代码应该用作vigenere密码。但是,在运行时,无论您输入什么输入,它都会出现分段错误。我正在为edx在线CS50课程写这篇文章。是否strncpy应该阻止分段错误发生,如果我告诉它复制适当的字符数量?在c中使用strncpy时出现分段错误
#include
#include
#include
#include
#include
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;
}
2016-01-24
Fluffy
+1
你为什么使用'strncpy()'?使用'strcpy()'或者如果你知道目标缓冲区的长度和源缓冲区的长度,确实也使用'memcpy()',除非字符串在循环内部改变,否则不要在循环中使用'strlen()'。 –
+0
@iharob使用strcpy()仍然会导致分段错误。此外,strlen()仅在循环开始时被调用一次,并且被保存为int n。 –
+0
在llp开始的时候这样做,它在我看来就像是'for'的条件。你在Linux上吗?或者mac?如果是这样,我建议[valgrind](http://www.valgrind.org),它应该可以帮助你快速发现问题。 –