BUG: in mallocr.c: overlapping realloc fails
Jeff Johnston
jjohnstn@redhat.com
Fri Jun 3 18:05:00 GMT 2005
Fery wrote:
> Hi,
>
> If I call realloc in a situation when realloc finds free space before
> the current block, and uses that, there is a possibility that the
> returned memory block will not contain the data the old memory block
> contained, if the following conditions exist:
>
> - the old and new memory blocks are overlapping
> - mallocr.c is compiled with HAVE_MEMCPY and USE_MEMCPY (this is the
> default on many platforms)
> - the block is larger than 9*sizeof(size_t)
> - the platform's memcpy() copies with decreasing addresses (e.g. SH2
> platforms).
>
This last point is the source of the problem. Normal memcpy implementations go
forward and thus, overlapping only occurs if the destination is after the
source, but before it's end. This can't occur in a realloc so no check was
necessary.
> As the memory blocks passed to memcpy() may not overlap, the overlapping
> must be checked, and in that case, the memory must be copied with an
> overlapping-safe method. Because overlapping can occur only if the
> destination block is before the source block, the internal MALLOC_COPY
> macro (if USE_MEMCPY macro equals to 0) would work without error.
>
I believe the simple answer is to use memmove () instead of memcpy (). The
memmove () implementation should be smart enough to check for overlapping and if
not, use the regular memcpy logic.
-- Jeff J.
More information about the Newlib
mailing list