title: Chopping Paths in C
body: <p>I want to preface this by saying that I've done very little programming in C, so I'd prefer to know why a given solution works rather than just what it is.</p>
  
  <p>I'm trying to write a function which will take a pathname, and return a pathname to a different file in the same directory. </p>
  
  <pre><code>  "/example/directory/with/image.png" =&gt; "/example/directory/with/thumbnail.png"
  </code></pre>
  
  <p>What I've tried after reading up on example uses of <code>realpath</code> and <code>dirname</code> (I'm working on Linux; if there's a cross-platform equivalent, let me know) is:</p>
  
  <pre><code>#include &lt;limits.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  char *chop_path(char *orig) {
    char buf[PATH_MAX + 1];
    char *res, *dname, *thumb;
  
    res = realpath(orig, buf);
    if (res) {
      dname = dirname(res);
      thumb = strcat(dname, "/thumbnail.png");
      return thumb;
    }
    return 0;
  }
  </code></pre>
  
  <p>Compiling it seems to work, but running the program with</p>
  
  <pre><code>int main(void) {
    char *res = chop_path("original.png");
    if (res) {
      printf("Resulting pathname: %s", res);
    } 
    return 0;
  }
  </code></pre>
  
  <p>gives me a segfault. Any hints?</p>