c - 检测到堆损坏 C

标签 c

我一直在使用 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/

相关文章:

java - 双指针 Android JNI

c - 如何使全局变量无法被 C 中的特定函数访问

c - 在不创建临时文件的情况下打开 gzip 文件以在 C 中读取

c - 如何通过更改参数来更改C中变量的值

c - 从 C 中的文件读取和打印时出现奇怪的输出

c - C中链表的两种不同情况

c - local_fiq_enable() 的功能

c - 这个C程序是如何工作的?

c - C中Server和Client之间用Ring Buffer(循环缓冲区)进行数据交换

c - 获取字符输入并将其存储在数组中