title: Random characters at the end of C read file
body: <p>I've been trying to read a file using code I got from <a href="https://stackoverflow.com/a/174552/14087854">this</a> answer.</p>
  <p>This is my code:</p>
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  char * readfile(FILE * f)
  {
      char * buffer = 0;
      long length;
      
  
      if (f)
      {
          fseek(f, 0, SEEK_END);
          length = ftell (f);
          fseek(f, 0, SEEK_SET);
          buffer = malloc(length);
          if (buffer) fread(buffer, 1, length, f);
          fclose(f);
      }
  
      return buffer;
  }
  
  int main()
  {
      FILE * f = fopen(&quot;./file.txt&quot;, &quot;r&quot;);
      printf(readfile(f));
  }
  </code></pre>
  <p>My function does return the contents of the file but it also returns random characters.</p>
  <pre><code>contents╪▐&gt;c☻ú
  </code></pre>
  <p>And amazingly they seem to change every time I run the code.</p>
  <pre><code>contents╗╙ÿ▓.┤
  </code></pre>
  <p>The contents of my file are &quot;contents&quot;.</p>
  <p>My question is: How can I fix my code for it not to return random characters?</p>