【发布时间】: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