我正在尝试释放我的文件名(char *
指针)但出现错误:
Heap corruption detected: after normal block (#65) at 0x....
代码:
static FILE *initializeIndexFile(char *database, char **indexFileName)
{
FILE *file1_p;
*indexFileName = NULL;
int len = strlen(database);
*indexFileName = (char *)malloc(len *sizeof(char) + 1);
strcpy(*indexFileName, database);
file1_p = fopen(strcat(*indexFileName, ".ind"), "rb");
if (file1_p == NULL)
Handle_Failure();
fclose(file1_p);
free(*indexFileName);
return file1_p;
}
首先,我解决了这个问题,因为文件仍然打开,所以我调用了 fclose()
,但它仍然遇到同样的错误。
最佳答案
你的代码在下面一行有问题
strcat(*indexFileName, ".ind")
*indexFileName
的目标缓冲区没有足够的内存来保存连接的字符串。因此它调用 undefined behaviour .
来自man page strcat()
... If dest (destination buffer) is not large enough, program behaviour is unpredictable;
因此,一旦它调用 UB,就没有您可以预测或预期的特定行为。
也就是说,
请do not cast
malloc()
和C
中的 family 的返回值。sizeof(char)
被C
标准保证为1
。你儿子不需要用那个。
解决方案 [来自deleted answer by 先生Mohit Jain ]
将您的分配修改为:
int len = strlen(database) + strlen(".ind"); //allocate enough space to hold
*indexFileName = (char *)malloc(len + 1); // the final concatenated string
关于fclose 后无法释放 fileName char *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30797174/