My code is working fine until I try to free the allocated memory. I malloced the files pointer, and later on I used realloc to increase the size. But then it gives me invalid pointer error when I try to free the memory, not sure why.
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;
This is the error I am getting,
======= 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: ========
Note: If I run the same code without freeing any memory space, it works fine. Which means that the pointers are pointing to the correct location in the memory.
strcat(temp, "/");.tempis only big enough for theargv[i]string that you copied it from, it doesn't have room for you to concatenate additional strings to it.