gpt4 book ai didi

c - 检测到堆损坏 C

转载 作者:行者123 更新时间:2023-11-30 20:22:45 25 4
gpt4 key购买 nike

我一直在使用 C 和一些密码学,无论如何,我尝试动态分配一个字符串来输入纯文本和一个用于获取密文的 key 。程序将一直运行,直到我决定释放分配的内存为止。然后产生一个错误,指出:HEAP CORRUPTION DETECTED: after Normal block (#73) at this and this address;检查了所有其他帖子,什么都没有,我很困惑,请帮忙。代码如下:

int main(int argc, char *argv[])
{
int plainSize = 0;
int keySize = 0;

InputInteger(keySize,"key size");
InputInteger(plainSize,"plaintext size");

char *plaintext = (char*)malloc((plainSize + 1) * sizeof(char));
char *key = (char*)malloc((keySize + 1) * sizeof(char));
char *cypher = (char*)malloc((plainSize + 1) * sizeof(char));

InputString(plaintext, "plaintext");
InputString(key, "key");


cypher=ViginereEncrypt(plaintext, key);
printf("\n%s encypted with Viginere key %s is %s", plaintext, key, cypher);
printf("\n\n");

free(plaintext);
free(key);
free(cypher);
}

char *ViginereEncrypt(char *plaintext,char *key)
{
int i = 0;
char *cypherText = (char*)malloc((strlen(plaintext) + 1)*sizeof(char));
printf("\n%d\n", strlen(plaintext) + 1);
for (i = 0;i < strlen(plaintext);i++)
*cypherText++ =(*plaintext++ - 'A' + *key++ - 'A' -1) % ('Z' - 'A') + 'A';
cypherText[i] = '\0';
return cypherText;
}
void InputInteger(int myInteger,char name [100])
{
printf("Input a number for %s : ",name);
scanf("%d", &myInteger);
}
void InputString(char myString[],char name[100])
{
printf("Input a string for %s : ",name);
scanf("%s", myString);
}

是函数内部的分配有问题吗?认为不应该,因为我将密码“复制”到函数返回,然后释放它。提前致谢!

最佳答案

函数调用 InputInteger(keySize,"key size"); 无法将值放入 keySizekeySizeplainSize 都将保留为 0。因此,您为每个字符串分配 1 个字节的内存,仅够作为终止符。电脑融化了。

我建议进行这些更改,首先传回输入值

void InputInteger(int *myInteger, char name [100])     // add the *
{
printf("Input a number for %s : ", name);
scanf("%d", myInteger); // remove the &
}

然后改变你的调用方式。

InputInteger(&keySize, "key size");                    // add the &
InputInteger(&plainSize, "plaintext size"); // add the &

以便您传递要更改的变量的地址。

编辑: 这并不是说代码中没有其他漏洞。字符串长度可能是负数,您应该进行一些输入验证。此外,InputString 函数容易遭受恶意攻击或意外故障,用户可以说字符串长度为 2,然后破坏堆栈,并使用一些奇怪的较大输入来接管机器,因为它是可执行的犯罪分子放置在那里窃取您的 Bean 的代码。

关于c - 检测到堆损坏 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38677120/

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