Question about dirent.h and static memory/leak

Yes I red that as well and with the information from the stackoverflow discussion I concluded that it must be wrong but I don't know why it works. No the whole function (using the malloc clobber) looks like this:

void find_all_folders_in_current_dir(char *path, struct files_and_folders *folders) {

DIR *current_directory = NULL; current_directory = opendir(path); struct files_and_folders *current; struct dirent *dir = NULL; dir = (struct dirent *)malloc(sizeof(struct dirent));

while((dir = readdir(current_directory)) != NULL) { char target = '.'; if(strrchr(dir->d_name, target) == NULL) { current->path = dir->d_name; current->next = (struct files_and_folders *)malloc(sizeof(struct files_and_folders)); current->next->prev = current; current = current->next; } }

free(dir); dir = NULL; closedir(currentDirectory); }

It just assigns stuff to a linked list. What I noticed running the debugger and why I even went to that function and tried to use malloc was because when I called this function later in the program after calling it before, it assigned previous d_name's from other function calls to the linked list and sometimes it just crashed on the readdir directly. It was like the function scope wasn't cleared somehow even though I mades sure I used closedir() every time it returns the function. Now the program runs perfectly and if I comment out the malloc for the dir (and free/null) , I get seg fault (btw on around 70% of the runs, not every run).

/r/C_Programming Thread Parent