Is realloc guaranteed to be in-place when the buffer is shrinking?

前端 未结 5 1094
遇见更好的自我
遇见更好的自我 2021-01-04 09:33

Are there any guarantees that realloc() will always shrink a buffer in-place?? So that the following:

new_ptr = (data_type *) realloc(old_ptr, new_size * siz         


        
5条回答
  •  生来不讨喜
    2021-01-04 10:09

    No.

    That's it. None of this "it may work in some architectures" or "it should, based on experience". The standard states clearly that the address may change so rely on that and nothing more. In any case, you asked if it was guaranteed - the answer that is a definite no(a).

    In terms of coding to the standard: do, or do not. There is no "try" :-)


    From c99:

    The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.

    If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

    The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated.


    (a) If you're wondering why you wouldn't just split up a buffer into two smaller buffers (keeping one and returning the other to the free list) for efficiency, there is at least one possibility that springs to mind.

    If you have different pools for allocations of different sizes (which may use different allocation strategies, for example), it might make sense to move the data over to the pool for smaller allocations. The efficiency gains you get from separate pools may outweigh the gains of leaving memory in place.

    But that's just an example, I have no idea whether any implementation does that. As stated, you should rely on what the standard mandates, which is that the memory may move even when shrinking.

提交回复
热议问题