【发布时间】:2015-12-29 18:49:45
【问题描述】:
我的程序接收一个二维字符串数组。在它完成它应该做的事情之后,我尝试释放为字符串分配的内存,但是当我尝试这样做时出现堆损坏错误。 这是我的代码:
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]);
我将在一天后到期,我很绝望! 谢谢。
【问题讨论】:
-
请正确格式化sn-p。
-
在第二次调用 malloc 时不应该为空终止符分配一个字节吗?
-
malloc(strlen(buffer)*sizeof(char));-->malloc(strlen(buffer)+1);。 C 字符串以 0 结尾。 (并简化,因为sizeof(char)定义为1。) -
你也不应该在 C 中转换
malloc的返回类型,如果你忘记包含它的标题,这可能会隐藏错误。 -
查看以
text = ...开头的三行。首先,text没有被声明。其次,gets已被弃用,第三,根据您已经输入的内容尝试重新分配text是没有用的。此时输入已经破坏了缓冲区。
标签: c string free heap-corruption