I'm having a problem in C when listing the files from a folder.
The strange here is that it works fine several times, but then the program is calling other functions and after that run again then the function to list the files.
I added a print malloc_usable_size - it says that has enough space but when it breaks out it says 0.
Also when is broken out the ent->d_name has some strange characters.
At the end finishes with an error: realloc(): invalid next size
Do you have any idea?
Here is the code:
struct dirent *ent;
int size = 6;
char *file_names = NULL, *temp = NULL;
while((ent=readdir(dirp))!=NULL) {
  if( (strcmp(ent->d_name, ".")!=0) && (strcmp(ent->d_name, "..")!=0) ) {
    size += strlen(ent->d_name)*sizeof(char) + 6;
    temp = file_names;
    file_names = (char *) realloc(file_names, size);
    if(file_names != NULL) {
      strcat(file_names, ent->d_name);
      strcat(file_names, "\n\0");
    }
    else {
      file_names = temp;
    }
  }
}
closedir(dirp);
if(file_names != NULL) {
  strcat(file_names, "\0");
}
 
     
     
    