Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Many memory allocation routines have a minimum-sized allocation block which they can support, and will expand any allocation request to that minimum size. While they could have had <code>malloc</code> check whether the size is zero and return null if it is, it was simpler and easier to have all malloc requests less than the minimum size (including those for exactly zero bytes) get padded out to the minimum size. Since the only code which would be likely to request a zero-byte malloc would be asking for a buffer whose size was determined at runtime, and since any such code would expect to free any buffer it had asked for without regard for its size, such behavior caused no difficulty.</p> <p>Another thing to consider is that if <code>realloc</code> is called on a block multiple times, it may be desirable to keep on using the same memory block if it has adequate space available. If a block which has e.g. 256 bytes allocated to it gets sized to zero, it may be desirable to hold off for awhile on using the formerly-occupied 256 bytes for any purpose other than re-expanding that memory block. If calling <code>realloc</code> on a memory block with a requested size of zero returns a pointer to that same block, then the system will be able to recognize a subsequent request to re-expand that block and use the formerly-occupied space to satisfy it. If the zero-byte <code>realloc</code> returned a null pointer, a request to expand that block to a non-zero size would be indistinguishable from a request to allocate a new one.</p> <p>Code which uses <code>realloc</code> (or anything <code>malloc</code> related, for that matter) will generally not have any control over memory allocation and recycling policy, but some implementations of the "malloc library" may benefit from having code which doesn't need something at the moment but will likely need it in future reallocate it to size zero rather than freeing it. Note that while the usage pattern which is best for one library may be sub-optimal in another, code which is uses "malloc library" functions in a standards-compliant fashion should work, even if not optimally, on any machine which implements them standards-compliant fashion. If one knows that for the next year or two a program is likely to be run on a machine with a particular allocator, it may be helpful to write the code in the way that's optimal for that allocator. The program might have in future have to run on a machine for which its allocation pattern is no longer optimal, but if that machine is faster and has more RAM (as will likely be the case), the suboptimal performance probably won't pattern.</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