Is realloc guaranteed to be in-place when the buffer is shrinking?
<p>Are there any guarantees that realloc() will always shrink a buffer in-place?? So that the following:</p>

<pre><code>new_ptr = (data_type *) realloc(old_ptr, new_size * sizeof(data_type));
</code></pre>

<p>will always give new_ptr == old_ptr if new_size &lt; old_size (except of course when new_size == 0). It seems sensible (to me) that it would work this way, but was curious whether the standard enforced it.</p>

<p>I'm looking at the reallocation of arrays of non-POD data types, and if the above behaviour was guaranteed was thinking that the following strategy might at least allow efficient "shrinking":</p>

<pre><code>if (new_size &gt; old_size)
{
    // malloc() a new buffer
    // use placement copy constructor to copy old objects over
    // free() old buffer
}
else
if (new_size &lt; old_size)
{
    // explicit destruction of unneeded objects
    // realloc() buffer
}
</code></pre>

<p>I"m expecting that an in-place "shrink" would be robust even if the data type had self references/pointers or whatever...</p>
