title: Should I free strdup pointer after basename/dirname in C?
body: <p>I want to use POSIX's <code>basename</code> function (as opposed to GNU's).</p>
  
  <p>From the man page:</p>
  
  <blockquote>
    <p>Both  dirname()  and  basename() may modify the contents of path, so
    it may be desirable to pass a copy when calling one of these functions.</p>
    
    <p>These functions may return pointers to statically allocated memory which may be overwritten by subsequent calls.   <strong>Alternatively,
    they  may return a pointer to some part of path</strong>, so that the string referred to by path should not be modified or freed until the
    pointer returned by the function is no longer required.</p>
  </blockquote>
  
  <p>It also says:</p>
  
  <blockquote>
    <p><strong>RETURN VALUE</strong><br>
           Both dirname() and basename() return pointers to null-terminated strings.  (<strong>Do not pass these pointers to free</strong>(3).)</p>
  </blockquote>
  
  <p>So the example suggests something like:</p>
  
  <blockquote>
    <p><strong>EXAMPLE</strong>  </p>
  
  <pre><code>       char *dirc, *basec, *bname, *dname;
         char *path = "/etc/passwd";
  
         dirc = strdup(path);
         basec = strdup(path);
         dname = dirname(dirc);
         bname = basename(basec);
         printf("dirname=%s, basename=%s\n", dname, bname);
  </code></pre>
  </blockquote>
  
  <p>The <code>strdup</code>(<code>strndup</code>) man page says:</p>
  
  <blockquote>
    <p>Memory for the new string is obtained with malloc(3), and can be freed with free(3).</p>
  </blockquote>
  
  <p>So the question is: Should I free dirc and basec (as per <code>strdup</code>) or not (as per <code>basename</code>)?</p>