1

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;
 }
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Hannu
  • 11,685
  • 4
  • 35
  • 51
  • 1
    I assume you have run the program in a debugger to find out that it's the `closedir` call that fails? If you run in a debugger, and compare the `directory` variable you receive with `opendir` with the same variable before the `closedir` call, are they still the same? – Some programmer dude May 24 '13 at 11:35
  • By the way, your final `if`-rake can be just `return c <= 2;`, using `if` to compute `1` or `0` is rarely needed. – unwind May 24 '13 at 11:36
  • Yep, it is the same. That's the weird thing that bugs me. I initially assumed internal memory corruption and checked this first. – Hannu May 24 '13 at 11:45
  • 1
    The code looks good. Just to double-check, this is the *only* code in your application? You're running it with `int main() { return is_dir_empty("..."); }`? Otherwise there could be heap corruption from some random unrelated code you're not showing us. – Nicholas Wilson May 24 '13 at 11:45
  • Also, valgrind is your friend. – Nicholas Wilson May 24 '13 at 11:46
  • @NicholasWilson thanks, it seems to be a problem elsewhere. That's what you get for not doing any C in 15 years or so.... – Hannu May 24 '13 at 11:51

0 Answers0