Cody
Cody

Reputation: 145

Can opendir(pathname) change the value of the input pathname?

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?

Upvotes: 2

Views: 444

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

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?

Upvotes: 3

Related Questions