Re: Adding a realloc() usage note to the malloc(3) manual page

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, 31 Aug 2021 at 11:29, Paul Eggert <eggert@xxxxxxxxxxx> 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/



[Index of Archives]     [Kernel Documentation]     [Netdev]     [Linux Ethernet Bridging]     [Linux Wireless]     [Kernel Newbies]     [Security]     [Linux for Hams]     [Netfilter]     [Bugtraq]     [Yosemite News]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux Admin]     [Samba]

  Powered by Linux