title: C program: Segmentation Fault when using opendir and readdir
body: <p>&nbsp;&nbsp;&nbsp; I am writing a simple program that opens the current directory you are working in and prints all the contents of the directory stream, and then takes other directories through the command line and prints the contents of their stream as well.  The problem is when I type in a false directory through the command line my program fails to print "Cannot Access <em>directory name</em>" and gives me "Segmentation Fault (core dumped)"</p>
  
  <h3>This is my Main class "myls.c"</h3>
  
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;dirent.h&gt;
  #include &lt;stdio.h&gt;
  #include "mylsFunctions.h"
  
  int main (int argc, char *argv[]) {
          printDirectoryContents("./.");
  
          for( int i = 1; i&lt;argc; i++)
                  printDirectoryContents(argv[i]);
  }
  </code></pre>
  
  <h3>Here is the file with my function used in the Main "mylsFunctions.c" </h3>    
  
  <pre><code>#include &lt;dirent.h&gt;
  #include &lt;stdio.h&gt;  
  #include &lt;sys/types.h&gt;
  #include &lt;stdlib.h&gt;
  #include "mylsFunctions.h"
  
  void printDirectoryContents (char *directory) {
      currentDirectory = opendir(directory);
      if(currentDirectory == NULL) {                         
              printf("Cannot Access %s",directory);
              exit(-1);
      }
      while ((entry=readdir(currentDirectory)) != NULL)
              printf("%s\n",entry-&gt;d_name);
      closedir(currentDirectory);
  }
  </code></pre>
  
  <h3>Here is the Header "mylsFunctions.h"</h3>
  
  <pre><code>#ifndef MYLSFUNCTIONS_H
  #define MYLSFUNCTIONS_H
  
  DIR *currentDirectory;
  struct dirent *entry;
  
  void printDirectoryContents(char *directory);
  #endif
  </code></pre>
  
  <p>~</p>