title: Security/performance implications of malloc over calloc?
body: <p>According to the Linux man page, the difference between <code>calloc</code> and <code>malloc</code> is that <code>malloc</code> does not initialize the memory, while <code>calloc</code> <em>does</em> initialize the memory. </p>
  
  <p>What that means in practice is that if I create a struct like this:</p>
  
  <pre><code>struct Danger {
      char a;
      char b;
      char c;
      char d;
  }
  </code></pre>
  
  <p>If I create it with <code>malloc</code>:</p>
  
  <pre><code>struct Danger *dang = malloc(sizeof(struct Danger));
  </code></pre>
  
  <p>It seems that <code>dang-&gt;a</code> could really be any value at this point, as the memory isn't initialized. If I use <code>calloc</code>:</p>
  
  <pre><code>struct Danger *dang = calloc(1, sizeof(struct Danger));
  </code></pre>
  
  <p>I know now that <code>dang-&gt;a</code> <em>must</em> equal <code>\0</code>. </p>
  
  <p>The reason <code>malloc</code> presumably exists is in the case that you'll be writing to the entire memory space you've allocated immediately, you don't really care about what's in there at first. This saves you an extra step of zeroing out the data which will be overwritten anyway</p>
  
  <p>It seems though, that from a program security and stability point of view, using <code>malloc</code> should be the exception rather than the rule, as it can easily lead to undefined behavior.</p>
  
  <p>Two questions:</p>
  
  <ul>
  <li>Do C programs in the wild deal with unexpected functionality as a result of <code>malloc</code> often? Is this a fairly recurrent problem?</li>
  <li>How much of a performance penalty do I really get if I just use <code>calloc</code> every time instead of <code>malloc</code>?</li>
  </ul>