I used a piece of code found here to check if a directory is empty or not. However, closedir() seems to cause a core dump on Ubuntu. Any ideas why?
The directory exists. Opendir returns a handle and readdir is able to access the directory with that handle and the function does what it is supposed to do. However, when I try to close the directory, the program crashes with error
*** glibc detected *** ./chelper: free(): invalid next size (normal): 0x00000000017f10b0 ***
My workaround at the moment is just leave the directory open as this is just a helper kludge to do a suid part of something bigger. It runs, does the suid part and exits. I just hate leaving things open...
root@honecker:~/Project# uname -a Linux honecker 3.5.0-31-generic #52~precise1-Ubuntu SMP Fri May 17 15:27:06 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
/* Check if mount point is empty true=empty false=not empty */
int is_dir_empty(char *path) {
int c=0;
struct dirent *dent=NULL;
DIR *directory=NULL;
directory = opendir(path);
if (directory == NULL) {
perror(PNAME);
exit(1);
}
while ((dent = readdir(directory)) != NULL)
if (++c > 2)
break;
if (closedir(directory) == -1) {
perror(PNAME);
exit(1);
}
if (c <= 2)
return 1;
else
return 0;
}