Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>C does not support zero-sized objects, but the argument to <code>malloc()</code> is of type <code>size_t</code>, and there's no good way to prevent a program from calling <code>malloc(0)</code>. It may not be the programmer's intent, but it's not necessarily literally <code>malloc(0)</code>; it's more likely to be <code>malloc(count)</code>, where <code>count</code> is the result of some computation.</p> <p>As for the standard permitting two different behaviors, that's simply because existing implementations (at the time the original standard was being written) did different things, and the authors wanted to avoid breaking existing code. Such code was arguably already broken, or at least non-portable, but by permitting either behavior a program that made assumptions about how <code>malloc(0)</code> behaves could continue to work <em>on the system for which it was written</em>.</p> <p>If you're looking for a coherent explanation, you're not going to find one. If C were being designed from scratch today, the behavior of <code>malloc(0)</code> almost certainly would have been nailed down, one way or the other. Either that, or the behavior would have been made undefined, but making it implementation-defined means that code doesn't have to check quite as carefully that it's not passing zero to <code>malloc()</code>.</p> <p>And in fact the committee's decision is documented in the <a href="http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf" rel="nofollow">C99 Rationale</a>, section 7.20.3, pages 160-161.</p> <p>It does mean that:</p> <pre><code>void *ptr = malloc(0); free(ptr); </code></pre> <p>will work correctly; <code>free()</code> does nothing if its argument is a null pointer.</p> <p>What can you do with the result of <code>malloc(0)</code>? Well, if <code>malloc(1024)</code> is successful, you can store 1024 bytes in the allocated space. You can store <em>no</em> bytes in the space allocated by <code>malloc(0)</code> -- which is exactly what you asked for.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload