Infinite loop calling recursive function

94 Views Asked by At

ok so I want to write a function that looks for all subdirectories given a directory as input. It accepts also an int so that it's possible to keep track of the levels. The return value should be a char* array with all subdirectories listed. I thought a recursive function would be preferrable, however I have trouble setting up the right algorithm. The program runs but at the second subdirectory it seems to block indefinitely. The code is as follows (dict is a struct mimicking hashmap):

char *search_dir(char* directory, int i) {
   struct dirent *de;
   DIR *dir;
   dir = opendir(directory);
   de = readdir(dir);
   struct stat st;
   struct dict *d = NULL, **l; //linked list
   l = &d;
   
   char *parent_name = malloc(MAXSIZE);
   char *pardir = (char*) malloc(sizeof(char*) * MAXSIZE);
   char *subdir = (char*) malloc(sizeof(char*) * MAXSIZE);
   memset(parent_name, "\0", sizeof(parent_name));
   char *result = malloc(MAXSIZE);
   if(dir != NULL) {
       while(de != NULL) {
           *l = malloc(sizeof(**l) * 500);
           lstat(de -> d_name, &st);
           if(S_ISDIR(st.st_mode)) {
                strcpy(parent_name, directory);
                printf("PARENT_NAME INIT %s\n", parent_name);
                (*l) -> key = parent_name;
                (*l) -> value = de -> d_name;
                printf("LVALUE%s\n", (*l) -> value);
                (*l) -> idx = i;
                strcpy(subdir, de -> d_name);
                printf("SUBDIR%s\n", subdir);
                sprintf(pardir, "%s%s", parent_name, subdir);
                printf("PARDIR%s\n", pardir);
                snprintf(subdir, "%s%s", pardir, subdir);
                i++;
                l = &(*l) -> next;
                search_dir(subdir, i);
                strcpy(result[i], pardir);
                if(d -> value == NULL) {
                    pardir = "\0"; // exit cycle
                    break;
                }
           }
      }
      free(*l);
      free(d);
  }
  free(parent_name);
  return result;

}

1

There are 1 best solutions below

0
Employed Russian On

The program runs but at the second subdirectory it seems to block indefinitely.

There are few problems with the program:

  1. For any given directory, it performs readdir() once, instead of actually looping over all entries.
  2. It doesn't ignore . and .. entries.
  3. It doesn't ever call closedir(), leaking memory.
  4. It leaks lots of malloced memory