gpt4 book ai didi

c - 尝试释放二维数组时发生堆损坏错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:18:21 26 4
gpt4 key购买 nike

我的程序接收一个二维字符串数组。在它完成它应该做的事情之后,我尝试释放分配给字符串的内存,但是当我尝试这样做时出现堆损坏错误。这是我的代码:

printf("Please enter the number of lines:");
scanf("%d", &length);
lines = (char**)malloc(length*sizeof(char*));//allocating memory for the array of strings "lines".
if (lines == NULL)
{
printf("Error! Not enough memory.");
return 0;
}
getchar();//needed in order to use "gets".
printf("Please enter your lines:\n");
for (i = 0; i < length; i++)
{
printf("%d.", i);
gets(buffer);//user inserts the string "buffer".
lines[i] = (char*)malloc(strlen(buffer)*sizeof(char));//allocating memory for the strings in the array according to the ength of the string "buffer".
if (lines[i] == NULL)
{
printf("Error! Not enogh memory.");
return 0;
}
strcpy(lines[i], buffer);//copies the string "buffer" into "lines[i]".
}
printf("Plese enter your comparison string:");
text = (char*)malloc(80 * sizeof(char) + 1);//allocating temporary memory for the string "text".
gets(text);//inserting the string "text".
text = (char*)realloc(text, strlen(text)*sizeof(char)+1);//reallocating the correct memory of "text" according to its exact length and adding an additional memory spot for the chat "\0".
cmpresult = isEquivalent(lines, length, text);//calling the function
if (cmpresult == TRUE)//if the function returned TRUE
printf("The strings are equal.\n\n");
else printf("The strings are not equal.\n\n");//if the function returned FALSE.
for ( i = 0; i < length; i++)//free the memory allocated for lines[i].
free(lines[i]);
free(lines);//free the memory allocated for the array "lines".
getchar(option);
}

调试后,我发现这是使我的程序崩溃的行。

for (i=0; i < length; i++)//free the memory allocated for lines[i].
free(lines[i]);

一天后预产期,我很绝望!谢谢。

最佳答案

有几个问题:

  1. 您没有为字符串分配足够的内存。正如 Weather Vane 所说,C 字符串以零结尾,您需要考虑到那个 '0' 并在每次为字符串分配位置时再分配一个字节。

  2. 不要使用 strcpy(),而是使用 strncpy()。这是为了安全问题。参见 Why should you use strncpy instead of strcpy?

  3. 出于同样的原因,不要使用gets()

  4. text 没有被释放(这是你原来的问题)

关于c - 尝试释放二维数组时发生堆损坏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34517159/

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