I am working to develop debug implementations of the four basic memory allocation routines malloc
, realloc
, calloc
, and free
(similar in operation to Electric Fence) to debug heap corruption on embedded systems which do not have the resources to run other memory debugging tools, or for which other tools do not exist (for instance, LynxOS 7.0 for PowerPC ships with GCC 4.6.3, and a proprietary implementation of glibc and libstdc++ which does not include the mtrace
family of functions).
The following is the source code for calloc, from calloc.c in GCC's libiberty.
PTR
calloc (size_t nelem, size_t elsize)
{
register PTR ptr;
if (nelem == 0 || elsize == 0)
nelem = elsize = 1;
ptr = malloc (nelem * elsize);
if (ptr) bzero (ptr, nelem * elsize);
return ptr;
}
Why are nelem
and elsize
both set equal to 1
if either equals 0
?
If I attempt to allocate 0
chunks of size n
or n
chunks with 0
size, wouldn't either case result in an aggregate allocation of 0
total bytes, and not 1
byte?