title: Segmentation fault occurs because of dirname api for some particular strings (like . and usr)
body: <p>I am seeing the occurrence of Segmentation Fault (segfault) in my program because of an api <code>dirname</code> I am using to split a path into directory and file name in my code written in C for Linux.</p>
  
  <p><code>dirmane</code> is used for getting the directory name and <code>basename</code> is used to get the file name, according to the instructions <a href="http://linux.die.net/man/3/dirname" rel="nofollow noreferrer">here</a>.</p>
  
  <p>The barebone code is given below, which compiles and runs fine on Linux.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #define _GNU_SOURCE         
  #include &lt;string.h&gt;
  
  void main (void)
  {
      char *dirc, *basec, *bname, *dname = NULL;
      char *path = "."; /* I compile this code, for different paths as given below*/
  
      dirc = strdup(path);
      basec = strdup(path);
      dname = dirname(dirc);
      if (dname == NULL)
      {
          /* precautionary check */
          printf("null pointer\n");
      }
      bname = basename(basec);
      printf("dirname=%s, basename=%s\n", dname, bname);
  }
  </code></pre>
  
  <p>I am providing different types of strings in the variable <code>path</code> to see how these are split in to 'directory' and 'file name'. I am expecting the end result according to the samples given in above link (pasted below for quick reference).</p>
  
  <p><a href="https://i.stack.imgur.com/6leIv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6leIv.jpg" alt="enter image description here"></a></p>
  
  <p>When I set path as any of the following samples then I get SegFault because of <code>dirname</code> (If I comment it out then I don't get segfault).</p>
  
  <pre><code>*path = "."
  *path = ".."
  *path = "usr"
  *path = "usr/"
  </code></pre>
  
  <p>According to the table above, I should not get SegFault but a pointer to '.' string by dirname for such cases. I am not able to get it, as segfault occurs. I added a check for null string as well, as you can see above, to catch any null pointer issue but the program does not reach there as well.</p>
  
  <p><strong>Let me know if I am missing something or some information is incomplete in this question.</strong></p>