无法在 C 中释放重新分配的内存

Could not Free Realloc Allocated Memory in C

在我尝试释放分配的内存之前,我的代码工作正常。我 malloc 编辑了 files 指针,后来我使用 realloc 来增加大小。但是当我尝试释放内存时它给了我无效指针错误,不知道为什么。

char *files = malloc(1);
char *temp = strdup(argv[i]);
strcat(temp, "/");
strcat(temp, dp->d_name);
DIR *child_dir;
child_dir = opendir (temp);

if (child_dir == NULL) {
    files = realloc(files, strlen(dp->d_name)+1);
    strcat(files, dp->d_name);
    strcat(files, "/");
} else {
    struct dirent *child_dp;
    while ((child_dp = readdir (child_dir)) != NULL) {
        if (!strcmp(child_dp->d_name, ".")
            || !strcmp(child_dp->d_name, ".."))
                continue;

        files = realloc(files, strlen(child_dp->d_name) + 1);
        strcat(files, child_dp->d_name);
        strcat(files, "/");
    }
}
close(fd[0]);
int n = write(fd[1], files, strlen(files));
free(temp); // free
free(files); // free
temp = NULL;
files = NULL;
return;

这是我遇到的错误,

======= Backtrace: =========
/lib64/libc.so.6(+0x721af)[0x7fa2e697c1af]
/lib64/libc.so.6(+0x77706)[0x7fa2e6981706]
/lib64/libc.so.6(+0x78453)[0x7fa2e6982453]
./myfind[0x40110c]
./myfind[0x400b02]
/lib64/libc.so.6(__libc_start_main+0xf5)[0x7fa2e692a6e5]
./myfind[0x400a09]
======= Memory map: ========

注意:如果我 运行 没有释放任何内存的相同代码 space,它工作正常。这意味着指针指向内存中的正确位置。

你正在用这段代码破坏你的堆:

char *temp = strdup(argv[i]);
strcat(temp, "/");
strcat(temp, dp->d_name);

strdup 仅为其复制的字符串分配足够的 space,但您随后将更多内容连接到末尾而无需重新分配以腾出空间。

当您在 if 条件下 realloc files 时,您也不会将 space 留给 NUL 终止符,尽管在大多数情况下您''ll get away with that (you should allocate the correct amount though)。

最后,在 else 案例的 while 循环中,每个 realloc 只为您要添加的东西分配足够的空间,而不是离开 space对于已经存在的内容(同样,没有 space 留给 NUL 终止符)。一段时间后,重复的误用肯定会导致堆损坏。