When I run this code through several entries of a directory, it usually returns 0, but in two directories (one Windows one in Unix) I keep getting a “Bad Address” error message. lstat and relative_path are not null and relative_path does point to a valid directory. This code worked on other directories. The directories don’t have any RWX restrictions. Prior to this I was able to call opendir and readdir without getting errors or NULL responses on these problem directories. Valgrind shows no memory leaks or other errors.
struct stat *this_lstat;
...
DIR *dir = opendir(path);
...
dptr = readdir(dir);
...
Note: relative_path == “./bin/Debug” at this point.
int return_code = lstat(relative_path, this_lstat);
if (return_code < 0) {
fprintf(stderr, "find: ");
perror(dptr->d_name); //printf("3"); //Error reading the file or directory
return NULL;
}
UPDATE: I added checks on malloc and realloc and now I get segmentation error on the lstat line itself. The error handling code is not called. Here is the stacktrace:
Program received signal SIGSEGV, Segmentation fault.
0xb76f2779 in ?? () from /lib/tls/i686/cmov/libc.so.6
(gdb) backtrace
#0 0xb76f2779 in ?? () from /lib/tls/i686/cmov/libc.so.6
#1 0xb76ead47 in __lxstat () from /lib/tls/i686/cmov/libc.so.6
#2 0x0804959c in lstat ()
#3 0x0804903c in walk_directory_tree (path=0x805b058 "./testmine",
findme=0x0, type_str=0x0, base_dir_searched=1, dirs_later_array=0x805b0d0)
at pfind.c:266
#4 0x08049106 in walk_directory_tree (path=0xbfa5cca3 ".", findme=0x0,
type_str=0x0, base_dir_searched=1, dirs_later_array=0x804b018)
at pfind.c:282
#5 0x08048c2a in main (ac=2, av=0xbfa5c8a4) at pfind.c:143
From what I can tell, the error is being caused by your failure to initialize the
this_lstatthat gets passed as the second parameter tolstat.The error string “Bad address” corresponds to the error code
EFAULT, which comes from passing an invalid pointer to a system call. So, either the path name being passed tolstatdoesn’t point to a valid null-terminated string in readable memory, or thestruct statbeing passed as the second parameter doesn’t point to valid writable memory.You seem to be passing an unitialized pointer, which is almost certainly pointing to invalid memory. Valgrind doesn’t complain because up until the system call, you haven’t done anything wrong—only when the kernel tries to access the memory does it realize its invalid.
To fix this, either allocate memory for the
struct statwithmalloc, or just pass a pointer to a variable on the stack instead of using a pointer: