tech-kern archive

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

kmem_calloc and overflow checks [was Re: [PATCH] netbsd32 swapctl, round 4]



   Date: Sun, 02 Feb 2014 16:43:49 +0100
   From: Jean-Yves Migeon <jeanyves.migeon%free.fr@localhost>

   Even functions like calloc(3) are not required to check for the overflow 
   themselves when you pass them (number of elements, sizeof elements).

   Overflow checks are rather cumbersome in C...

Calloc(3) may not check, but we could define the semantics of
kmem_calloc to guarantee an overflow check in order to make it less
cumbersome for callers.

void *
kmem_calloc(size_t n, size_t size, km_flag_t flags)
{

        KASSERT(size != 0);
        if (n > (SIZE_MAX / size))
                return NULL;

        return kmem_zalloc((n * size), flags);
}

Of course, callers of kmem_calloc(..., KM_SLEEP) would have to check
for failure, but that's easier than doing arithmetic to check for
overflow.


Home | Main Index | Thread Index | Old Index