title: Problems grabbing file names using SDL_strdup and similar
body: <p>I'm trying to create a program with SDL2.<br>
  In a certain part of the code, I'm writing functions to grab names of all present files in a given directory path (and keep them in memory) so that, in another function, I can check if a specified file was present the last moment the directory was checked.
  I'm using <code>dirent.h</code> to suit my needs but I'm running into a few problems:</p>
  
  <ol>
  <li>All the files are properly captured by <code>readdir()</code> (no exception), however they aren't <em>always</em> properly copied into memory after using <code>SDL_strdup()</code> (code is below).</li>
  <li>I'm using <code>SDL_malloc()</code>/<code>SDL_realloc()</code>/<code>SDL_strdup()</code> to be as cross-platform as possible to avoid having problems when porting code (as I've read that strdup isn't C standard).</li>
  </ol>
  
  <p>Here's my code:</p>
  
  <pre><code>typedef struct FileList {
      char **files;
      size_t num;
  } FileList;
  
  FileList *GetFileList(const char *path){
  struct dirent *dp = NULL;
  DIR *dir = NULL;
  size_t i = 0;
  FileList *filelist = SDL_malloc(sizeof(FileList)); /* changing this to a calloc doesn't help */
  
  /* Check if filelist == NULL */
  filelist-&gt;files = NULL;
  
  dir = opendir(path);
  /* Check if dir == NULL */
  while ((dp = readdir(dir))){
      if (dp-&gt;d_name[0] == '.'){
          continue;    /* skip self, parent and all files starting with . */
      }
  
      printf("Copying: %s\n", dp-&gt;d_name); /* Always show the name of each file */
      filelist-&gt;files = SDL_realloc(filelist-&gt;files, ++i);
      filelist-&gt;files[i-1] = SDL_strdup(dp-&gt;d_name);
      printf("Copied: %s\n\n", filelist-&gt;files[i-1]); /* Varies: either shows the file's name, either gives me plain gibberish or just nothing */
  }
  filelist-&gt;num = i;
  
  closedir(dir);
  
  return filelist;
  </code></pre>
  
  <p>}</p>
  
  <p>Output varies. When it doesn't crash, I either get all filenames correctly copied, or I get most of them copied and some contain nothing or plain gibberish (as commented);  if it does crash, sometimes I get a Segfault while using <code>SDL_strdup()</code>, other times I get a Segfault when using <code>closedir()</code>.</p>
  
  <p>I've even considered exchanging the <code>SDL_realloc()</code> scenario with an initial memory allocation of <code>filelist-&gt;files</code> by giving it the number of files (thanks to another function) but I get the same problem.</p>
  
  <p>Any suggestion to change my coding style to a more defensive one (since I do believe this one is rather dangerous) will be appreciated, although I've tried all I could for this case. I'm currently working on a Mac OS X using built-in gcc Apple LLVM 6.0 (clang-600.0.56).</p>