title: Specifically, what's dangerous about casting the result of malloc?
body: <p>Now before people start marking this a dup, I've read all the following, none of which provide the answer I'm looking for:</p>
  
  <ol>
  <li><a href="http://c-faq.com/malloc/mallocnocast.html" rel="noreferrer">C FAQ: What's wrong with casting malloc's return value?</a></li>
  <li><a href="https://stackoverflow.com/questions/953112/should-i-explicitly-cast-mallocs-return-value">SO: Should I explicitly cast malloc()’s return value?</a></li>
  <li><a href="https://stackoverflow.com/questions/108768/needless-pointer-casts-in-c">SO: Needless pointer-casts in C</a></li>
  <li><a href="https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc">SO: Do I cast the result of malloc?</a></li>
  </ol>
  
  <p>Both the C FAQ and many answers to the above questions cite a mysterious error that casting <code>malloc</code>'s return value can hide; however, none of them give a specific example of such an error in practice.  Now pay attention that I said <strong>error</strong>, not <strong>warning</strong>.</p>
  
  <p>Now given the following code:</p>
  
  <pre><code>#include &lt;string.h&gt;
  #include &lt;stdio.h&gt;
  // #include &lt;stdlib.h&gt;
  
  int main(int argc, char** argv) {
  
      char * p = /*(char*)*/malloc(10);
      strcpy(p, "hello");
      printf("%s\n", p);
  
      return 0;
  }
  </code></pre>
  
  <p>Compiling the above code with gcc 4.2, with and without the cast gives the same warnings, and the program executes properly and provides the same results in both cases.</p>
  
  <pre><code>anon@anon:~/$ gcc -Wextra nostdlib_malloc.c -o nostdlib_malloc
  nostdlib_malloc.c: In function ‘main’:
  nostdlib_malloc.c:7: warning: incompatible implicit declaration of built-in function ‘malloc’
  anon@anon:~/$ ./nostdlib_malloc 
  hello
  </code></pre>
  
  <p><strong>So can anyone give a specific code example of a compile or runtime error that could occur because of casting <code>malloc</code>'s return value, or is this just an urban legend?</strong></p>
  
  <p><strong>Edit</strong> I've come across two well written arguments regarding this issue:</p>
  
  <ol>
  <li>In Favor of Casting: CERT Advisory: <a href="https://www.securecoding.cert.org/confluence/display/c/MEM02-C.+Immediately+cast+the+result+of+a+memory+allocation+function+call+into+a+pointer+to+the+allocated+type" rel="noreferrer">Immediately cast the result of a memory allocation function call into a pointer to the allocated type</a></li>
  <li><a href="http://www.cpax.org.uk/prg/writings/casting.php" rel="noreferrer">Against Casting</a>  (404 error as of 2012-02-14: use the <a href="http://web.archive.org/web/20100127165350/http://www.cpax.org.uk/prg/writings/casting.php" rel="noreferrer">Internet Archive Wayback Machine</a> copy from 2010-01-27.{2016-03-18:"Page cannot be crawled or displayed due to robots.txt."})</li>
  </ol>