reallocarray (3)
Leading comments
Copyright (c) 1980, 1991, 1993 The Regents of the University of California. All rights reserved. This code is derived from software contributed to Berkeley by the American National Standards Committee X3, on Information Processing Systems. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions ...
NAME
reallocarray - memory allocation and deallocationLIBRARY
Lb libbsdSYNOPSIS
In stdlib.h (See libbsd(7) for include usage.) Ft void * Fn reallocarray void *ptr size_t nmemb size_t sizeDESCRIPTION
When using Fn malloc be careful to avoid the following idiom:
if ((p = malloc(num * size)) == NULL) err(1, "malloc");
The multiplication may lead to an integer overflow, which can be avoided using the extension Fn reallocarray , as follows:
if ((p = reallocarray(NULL, num, size)) == NULL) err(1, "malloc");
Alternatively Fn calloc is a more portable solution which comes with the cost of clearing memory.
If Fn malloc must be used, be sure to test for overflow:
if (size && num > SIZE_MAX / size) { errno = ENOMEM; err(1, "overflow"); }
The use of Fn reallocarray or Fn calloc is strongly encouraged when allocating multiple sized objects in order to avoid possible integer overflows.