gpt4 book ai didi

c - 编码维吉尼亚密码时c中的段错误

转载 作者:行者123 更新时间:2023-11-30 15:07:47 25 4
gpt4 key购买 nike

我对编码非常陌生,我一直在自学如何使用 EDX.org 进行编码。这周我一直在学习密码学,我必须创建一个维吉尼亚密码。我写了代码,大部分都是正确的。但是,当我编译该程序时,它显示了段错误。我一直试图弄清楚为什么会发生这种情况,但我完全陷入困境。你能看一下我的代码并告诉我出了什么问题吗?

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


int index(int k, int c);

int main (int argc, string argv[1])
{
//check for correct criteria
if (argc = 2, isalpha(argv[1]))
{
string text = GetString();
string key = argv[1]; //store key word
int Totalshift = strlen(key); //number of shift for keyword


int shift = 0;

//loops over the whole text
for (int i = 0, n = strlen(text); i <n; i++ )
{
char p= text[i];
char k = toupper(key[shift]); //Upper case for each character

if (isupper(p))
{
//convert to 0 index
p = p - 65;
k = k - 65;

int crypt= index (k , p);

printf("%c", crypt+65);

shift= (shift+1) %Totalshift;
}
else if (islower(p))
{

p = p - 97;
k = k - 65;

int crypt= index (k , p);

printf("%c", crypt+97);

shift= (shift+1) %Totalshift;
}
else
{
printf("%c", p);
}


}
printf("\n");
}




//error message
else
{
printf("ERROR!\n");
return 1;
}


}

//index function
int index(int k, int p)
{
return (k+p)% 26;

}

最佳答案

字符串

不。 永远不要隐藏指针。

int main(int argc, char ** argv)

然后:

//check for correct criteria 
if (argc = 2, isalpha(argv[1]))

在这里,您分配给变量(在这方面,参数的行为类似于局部变量)值2,从而破坏之前的值(它保存参数的数量)给程序)。结果是分配的值,即 2。然后,有comma operator :您丢弃 2,然后调用 isalpha(argv[1]),这清楚地表明了为什么您应始终打开警告 和 < strong>永远、永远隐藏指针:

argv[1] 的类型为 char *,因此是一个指向字符数组的指针(或者,正如我们在本例中知道的那样) ,以 '\0' 结尾的字符数组,称为 C 字符串)。自 isalpha takes an int as parameter指针的值(“内存地址”)被隐式转换为(可能非常大)int 值。引用上面的链接,强调我的:

The c argument is an int, the value of which the application shall ensure is representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

这可能是段错误的根源。

最后,GetString 对我来说确实看起来很可疑。假设它分配了一些内存(用于它可能从用户读取的字符串)...您在哪里释放该内存?它是否真的分配内存,或者可能返回一个指向具有自动存储持续时间的数组的指针(可以说是局部变量)?

关于c - 编码维吉尼亚密码时c中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37954218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com