할당 된 메모리를 해제 할 때까지 내 코드가 제대로 작동합니다. I malloc
에 files
포인터를 편집 한 후 나중에 크기를 늘리기 위해 realloc
을 사용했습니다. 그런데 왜 메모리를 해제하려고 할 때 잘못된 포인터 오류를 발생시킵니다. 그 이유는 확실하지 않습니다. C에서 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]'문자열에 대해서만 충분히 크며, 추가 문자열을 연결할 수있는 여유가 없습니다. – Barmar