2

I've received some curious results while using opendir():

int dtw(char *path) {

    struct stat statbuf;

    ...

    else if (S_ISDIR(statbuf.st_mode)) {
            printf("Path is: %s\n", path);

            struct dirent *dirent;
            DIR *dirp;

            if ((dirp = opendir(path)) == NULL) {
                puts("Can't open directory.");
                return -1;
            }

            printf("Path is: %s\n", path);
    }

    ...
}

Results in:

Path is: /home/.../etc
Path is:

The only thing that would affect path is opendir() here. Does it have side effects that I'm not seeing? Or is there something else at work?

Jacob Schoen
  • 14,034
  • 15
  • 82
  • 102
Cody
  • 135
  • 1
  • 3
  • 11
  • 1
    How did you declare and initialize `path`? – sarnold Mar 16 '12 at 02:19
  • `path` is parsed from the command line and eventually passed into the relevant function from `main()`. Question edited to reflect that. – Cody Mar 16 '12 at 02:22

1 Answers1

3

No changes are allowed; the definition of opendir() is:

DIR *opendir(const char *dirname);

And the const says opendir() did not change it.

I wonder if your path is a pointer to freed memory? In that case, the memory may have been allocated to opendir() and you are seeing the change because you're using a dangling pointer to memory that you should not be looking at?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Ah, that's exactly it. This is the first time I've come across that kind of problem since switching from Java to C. Thank you very much. – Cody Mar 16 '12 at 02:30