Adding a realloc() usage note to the malloc(3) manual page
Michael Kerrisk (man-pages)
mtk.manpages@gmail.com
Thu Sep 2 00:21:32 GMT 2021
On Tue, 31 Aug 2021 at 11:29, Paul Eggert <eggert@cs.ucla.edu> wrote:
>
> On 8/31/21 12:07 AM, Florian Weimer wrote:
> > the somewhat common idiom of adjusting internal pointers in the
> > allocation to point to the new allocation is invalid.
>
> Good point.
Yes, thanks, Florian.
> Also, the example call to malloc should check the return value.
yes...
> Something like this, perhaps:>
> char *ptr = malloc(origsize);
> if (ptr == NULL)
> return NULL;
> char *p = ptr + some_random_value();
>
> /* In the following, we presume 'newsize' is not 0.
> (If 'newsize' is zero, realloc() may return NULL,
> and that is not an error.) */
>
> ptrdiff_t p_offset = p - ptr;
> char *nptr = realloc(ptr, newsize);
> if (nptr == NULL) {
> /* Handle error; the block pointed to by 'ptr' is
> still usable. */
> } else {
> /* realloc() succeeded; update 'ptr' and 'p' to point to
> the (possibly moved) block. 'p += nptr - ptr; ptr = nptr;'
> would be invalid here, since 'ptr' is invalid immediately
> after the successful realloc(). */
I don't get something here. Obviously, '*ptr' is invalid after a
successful realloc(). But why is 'ptr' invalid?
Thanks,
Michael
> ptr = nptr;
> p = nptr + p_offset;
> }
--
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Linux/UNIX System Programming Training: http://man7.org/training/
More information about the Libc-alpha
mailing list