![](/img/trans.png)
[英]CS50 / BEGINNER - Segmentation fault in nested for loop in C
[英]Core Dump (Segmentation fault) in this little encryption program I wrote in C for cs50
用戶輸入明文后發生錯誤。 我對這種語言和編程本身很陌生。 幫助將不勝感激。 由於我在 cs50 代碼空間中工作,因此由於某種原因我無法使用調試器,並且無法看到代碼轉儲,因為另一個問題建議我可以自己解決問題。 在這里待了幾天,現在不得不發布一個問題。 謝謝。
bool no_repeat(string key, int l);
string cipher(string key, string input, int l);
int main(int argc, string argv[])
{
if (argc == 2)
{
string key = argv[1];
int l = strlen(key);
int ver = 0;
for (int i = 0; i < l; i++)
{
if (isalpha(key[i]))
{
ver++;
}
}
bool c = no_repeat(key, l);
if (strlen(argv[1]) == 0)
{
printf("Please enter an encryption key.\n");
return 1;
}
else if ((l != 26) || (ver != 26) || (c == false))
{
printf("Please input a correct encryption key.\n");
return 1;
}
}
else if (argc == 1)
{
printf("Please enter an encryption key.\n");
return 1;
}
string key = argv[1];
int l = strlen(key);
string input = get_string("plaintext:");
string cipherText = cipher(key, input, l);
printf("ciphertext: %s\n", cipherText);
return 0;
}
bool no_repeat(string key, int l)
{
for(int i = 0; i < l; i++)
{
for (int k = i+1; k < l; k++)
{
if (key[i] == key[k])
{
return false;
}
}
}
return true;
}
string cipher(string key, string input, int l)
{
string output = "";
string alphabets = "abcdefghijklmnopqrstuvwxyz";
for(int i = 0 ; i < l ; i++)
{
int isUpper = isupper(key[i]);
key[i] = tolower(key[i]);
for (int k = i ; k < l ; k++)
{
if (input[i] == alphabets[k])
{
output[i] = key[k];
}
else
{
output[i] = input[i];
}
}
if (isUpper != 0)
{
output[i] = toupper(output[i]);
}
}
return output;
}
string
可能是typedef char * string;
在這種情況下,您不能修改string output = "";
. 相反,您想使用malloc()
分配足夠大的字符串,即:
string output = malloc(strlen(input) + 1);
if(!output) {
printf("malloc failed\n");
exit(1);
}
在 cipher() 你也在做input[i]
但i
從0
到strlen(key)
所以你可能會導致越界訪問。 對我來說, cipher() 正在返回密文的輸入。 這是固定版本(注意,這里刪除了參數l
並從調用者那里刪除了,因為它不需要):
string cipher(string key, string input) {
string output = malloc(strlen(input) + 1);
if(!output) {
printf("malloc failed\n");
exit(1);
}
const string alphabet = "abcdefghijklmnopqrstuvwxyz";
size_t j = 0;
for(size_t i = 0; i < strlen(input); i++, j++) {
string pos = strchr(alphabet, tolower(input[i]));
if(!pos) {
printf("letter %c not found in alphabet\n", input[i]);
exit(1);
}
output[j] = key[pos - alphabet];
}
output[j] = '\0';
return output;
}
和示例執行:
~$ ./a.out abcdefghijklmnopqrtsuvwxzy # swap s and t
plaintext:test
ciphertext: sets
順便說一句,您不必像 ASCII pos - alphabet
與tolower(input[i]) - 'a'
值相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.