This is a simplified code of my function:
myList* listFilesInDirectory(char* path) {
DIR* dir = opendir(path);
myList* list = createList();
struct dirent* entry;
while ((entry = readdir(dir)) != NULL) {
myNode* node = createNode(entry->d_name);
addToList(list, node);
}
closedir(dir);
return list;
}
that I use in main function:
myList* sourceFiles = listFilesInDirectory("source/");
myList* destFiles = listFilesInDirectory("dest/");
The problem is that second invocation of function changes elements of list that was returned in first invocation. Elements of sourceFiles
become changed after listFilesInDirectory("dest/");
is called.
But when I remove a closedir(dir)
from function body, then everything works correctly and elements of sourceFiles
are not changed.
I prepared a simple program https://pastebin.com/9pTYmpm2 so you can see what happens. Example result:
As you see, SourceFiles content 1
and SourceFiles content 2
are different. The first was printed before listFilesInDirectory("dest/")
was invoked, and the second was printed after. But if I remove closedir(dir)
from function all works correctly:
What is going on here? Why does it happen? How to prevent it? Should I not use closedir()
in my programs?
The problem seems to be that you are creating your node with the name straight from entry->d_name
. But entry is stack allocated struct
which will become invalid once your exit listFilesInDirectory
.
An easy fix:
while ((entry = readdir(dir)) != NULL) {
myNode* node = createNode(strdup(entry->d_name));
addToList(list, node);
}
But I suggest you check the return values of everything: opendir
, closedir
, as well as strdup
.