请转到第 29 行并阅读评论。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* messenges[5];
char* allstrings;
register int i;
int total = 0;
for (i = 0; i < 5; i++)
{
printf("Enter a string: ");
messenges[i] = (char*)malloc(5 * sizeof(char));
scanf("%s", messenges[i]);
total += strlen(messenges[i]);
}
allstrings = (char*)malloc(total);
strcpy(allstrings, messenges[0]);
for (i = 1; i < 5; i++)
{
strcat(allstrings, " ");
strcat(allstrings, messenges[i]);
}
printf("%s", allstrings);
free(allstrings); // This does not work..WHY?(Visual Studio 2015)
for (i = 0; i < 5; i++)
{
free(messenges[i]);// This works fine.
}
getch();
return 0;
}
上面的代码不会释放allstrings,但它可以释放messenges[i]。为什么它不适用于allstrings?
最佳答案
它可能会失败,因为您似乎忘记了 C 中的 char
字符串实际上称为空终止字节字符串. 空终止符部分非常重要,它需要一个额外的字节,否则你会写出越界。
越界写入会导致undefined behavior ,并且可能会覆盖内存分配器使用的内部数据,导致free
“不起作用”。
关于c - 为什么我的 free() 函数不起作用(代码如下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48258399/