【问题标题】:Could not Free Realloc Allocated Memory in C无法在 C 中释放 Realloc 分配的内存
【发布时间】:2018-03-26 03:59:56
【问题描述】:

在我尝试释放分配的内存之前,我的代码运行良好。我malloced 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: ========

注意:如果我在不释放任何内存空间的情况下运行相同的代码,它可以正常工作。这意味着指针指向内存中的正确位置。

【问题讨论】:

  • 您在执行strcat(temp, "/"); 时会导致未定义的行为。 temp 只够容纳您从中复制它的 argv[i] 字符串,它没有空间让您将其他字符串连接到它。

标签: c heap-memory realloc heap-corruption


【解决方案1】:

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

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

当您在 if 条件下 realloc files 时,您也不会为 NUL 终止符留出空间,尽管在大多数情况下您会侥幸逃脱(尽管您应该分配正确的数量)。

最后,在else 案例的while 循环中,每个realloc 只为您要添加的内容分配足够的空间,但没有为已经存在的内容留出空间(同样,没有空间剩余对于NUL 终结器)。反复的误用会在一段时间后保证堆损坏。

【讨论】:

  • “在大多数情况下你会侥幸逃脱”,我不确定这可能不会留下错误的印象......也许括号应该是( “如果你没有分配正确的内存——你应该被枪毙!”),或者只是“——未定义的行为结果”:)跨度>
  • @DavidC.Rankin:是的,我只是指出有些错误通常不会在某些或所有编译器/系统上引起症状,因此“它有效”不足以说代码是正确的。
  • 是的,我理解你所说的关键,这周五晚上让我觉得有点奇怪/幽默(因此:)
猜你喜欢
  • 2016-11-16
  • 2014-03-07
  • 1970-01-01
  • 2021-11-25
  • 2012-02-28
  • 2020-11-13
  • 1970-01-01
  • 2022-01-06
相关资源
最近更新 更多