此代碼應該用作vigenere密碼。但是,在運行時,無論您輸入什麼輸入,它都會出現分段錯誤。我正在爲edx在線CS50課程寫這篇文章。是否strncpy
應該阻止分段錯誤發生,如果我告訴它複製適當的字符數量?在c中使用strncpy時出現分段錯誤
#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;
}
你爲什麼使用'strncpy()'?使用'strcpy()'或者如果你知道目標緩衝區的長度和源緩衝區的長度,確實也使用'memcpy()',除非字符串在循環內部改變,否則不要在循環中使用'strlen()'。 –
@iharob使用strcpy()仍然會導致分段錯誤。此外,strlen()僅在循環開始時被調用一次,並且被保存爲int n。 – Fluffy
在llp開始的時候這樣做,它在我看來就像是'for'的條件。你在Linux上嗎?或者mac?如果是這樣,我建議[valgrind](http://www.valgrind.org),它應該可以幫助你快速發現問題。 –