Jun said:
Harald said:
CBFalconer wrote: [...]
void *calloc(size_t n, size_t s) {
void *result;
size_t sz;
result = NULL;
if (SIZE_MAX / n < s) {
What if n == 0 ?
That should be
if (n == 0 || s == 0 || SIZE_MAX / n > s) {
or something like that.
The version I have just put in nmalloc.c (not yet published) is:
/* calloc included here to ensure that it handles the
same range of sizes (s * n) as does malloc. The
multiplication n*s can wrap, yielding a too small
value, so we must ensure calloc rejects this.
*/
void *ncalloc(size_t n, size_t s)
{
void *result;
size_t sz;
result = NULL;
if (!n || ((size_t)-1) / n > s) {
sz = n * s;
if ((result = nmalloc(sz))) memset(result, 0, sz);
}
return result;
} (* ncalloc *)
which makes the output of ncalloc be that of nmalloc(0) whenever
either n or s is 0. I think there is still a possible glitch when
((size_t)-1) / n) == s. The only thing that needs protection
agains n==0 is the division. s==0 will simply force sz==0.