Main index | Section 3 | Options |
#include <stdlib.h>
if ((p = malloc(num * size)) == NULL) err(1, "malloc");
A drop-in replacement is the OpenBSD extension reallocarray():
if ((p = reallocarray(NULL, num, size)) == NULL) err(1, "reallocarray");
When using realloc(), be careful to avoid the following idiom:
size += 50; if ((p = realloc(p, size)) == NULL) return (NULL);
Do not adjust the variable describing how much memory has been allocated until the allocation has been successful. This can cause aberrant program behavior if the incorrect size value is used. In most cases, the above sample will also result in a leak of memory. As stated earlier, a return value of NULL indicates that the old object still remains allocated. Better code looks like this:
newsize = size + 50; if ((newp = realloc(p, newsize)) == NULL) { free(p); p = NULL; size = 0; return (NULL); } p = newp; size = newsize;
As with malloc(), it is important to ensure the new size value will not overflow; i.e. avoid allocations like the following:
if ((newp = realloc(p, num * size)) == NULL) { ...
Instead, use reallocarray():
if ((newp = reallocarray(p, num, size)) == NULL) { ...
REALLOCARRAY (3) | May 1, 2015 |
Main index | Section 3 | Options |
Please direct any comments about this manual page service to Ben Bullock. Privacy policy.
“ | If you have any trouble sounding condescending, find a Unix user to show you how it's done. | ” |
— Scott Adams |