fclose 后无法释放 fileName char *

标签 c memory-management malloc free realloc

我正在尝试释放我的文件名(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,就没有您可以预测或预期的特定行为。

也就是说,

  1. do not cast malloc()C 中的 family 的返回值。

  2. 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/

相关文章:

Swift <uninitialized> let 属性

c - 用户空间中的物理内存管理?

c - malloc 调用 realloc,然后崩溃

iphone - MonoTouch 中的内存泄漏消息 - 我必须处理这些消息吗?

C 指针 "type ** name"与 "type * name[]"作为参数

c - 段错误问题。尝试在 C 中实现双向链表 FIFO 队列

c - 双指针作为函数的数组

c++ - C/C++ 旋转 BMP 图像

ios - Objective C float 与 int、CGPoint 与基于自定义 int 的结构性能

c++ - C++中extern "C"有什么作用?