title: C - is calling getcwd causing a bug here?
body: <p>I'm learning syscalls like stat and readlink. I try to stat the root directory in two different ways:</p>
  <ol>
  <li>Just stat the path to root. Simple.</li>
  <li>Then, a roundabout way, fopen &quot;/&quot;, make a file descriptor path from the fd I get and readlink it to get &quot;/&quot;. Then stat.</li>
  </ol>
  <p>What I don't understand is this works the way I expect and the inode numbers are the same, except when I introduce more code AFTERWARDS, namely getcwd, the inodes are strangely not the same and test 2 fails. If you run both versions, with and without the part it says to cut out, the printf of p2 also changes and you can see there is garbage after <code>/</code>. What am I doing wrong here or what's going on here? How is code after those initial statements causing a change earlier in the code?</p>
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;limits.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  int main()
  {
      /* Stat root this way */
      struct stat st1;
      char *p1 = &quot;/&quot;;
      if (!stat(p1, &amp;st1))
          printf(&quot;PASS\n&quot;);
      else
          printf(&quot;FAIL - %m\n&quot;);
  
      /* Stat root another way */
      struct stat st2;
      char fdpath[100], p2[100];
      FILE *fp = fopen(&quot;/&quot;, &quot;r&quot;);
      sprintf(fdpath, &quot;/proc/self/fd/%d&quot;, fileno(fp));
      readlink(fdpath, p2, sizeof(p2));
      if (!stat(p2, &amp;st2))
          printf(&quot;PASS\n&quot;);
      else
          printf(&quot;FAIL - %m\n&quot;);
  
      printf(&quot;p2 = %s\n&quot;, p2);
  
      /* Check inodes are the same */
      printf(&quot;    st1.st_ino = %ld\n&quot;, st1.st_ino);
      printf(&quot;    st2.st_ino = %ld\n&quot;, st2.st_ino);
  
      /* TRY WITHOUT THIS - Adding this makes the inodes different! Take it out and they're the same */
      char cwd_buf[100];
      char *cwd_ret = getcwd(cwd_buf, sizeof(cwd_buf));
      if (cwd_ret == NULL)
          printf(&quot;getcwd failed - %m\n&quot;);
      printf(&quot;cwd_ret = %s\n&quot;, cwd_ret);
  
      return 0;
  }
  </code></pre>