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

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

 



Hello all,

I plan to add a note on the correct usage of realloc() to the
malloc(3) manual page. I would be happy to receive comments and
improvements to the text below.

Thanks,

Michael


   Correct usage of realloc() (and reallocarray())
       Since, on the one hand, realloc() (and  reallocarray())  may  move
       the block of memory, and on the other, it may return NULL on fail‐
       ure and leave the memory contents and location unchanged,  correct
       usage is something like the following:

           void *ptr, *nptr;
           ptr = malloc(origsize);
           ...
           /* In the following, we presume 'newsize' is not 0.
              (If 'newsize' is zero, realloc() may return NULL,
              and that is not an error.) */

           nptr = realloc(ptr, newsize);
           if (nptr == NULL) {
               /* Handle error; the block pointed to by 'ptr' is
                  still usable. */
           } else {
               /* realloc() succeeded; update 'ptr' to point to
                  the (possibly moved) block. */
               ptr = nptr;
           }

       Similar remarks apply for reallocarray().
-- 
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