Re: [PATCH] ALSA: Remove subsystem-specific malloc (1/8)

dean gaudet
2004-06-10T05:08:37Z

On Wed, 9 Jun 2004, Pekka Enberg wrote:

> +void *kcalloc(size_t n, size_t size, int flags)
> +{
> + if (n != 0 && size > INT_MAX / n)
> + return NULL;

division isn't very efficient :) it's typically a 40+ cycle operation.

there's almost certainly more efficient ways to do this with per-target
assembly... but you should probably just crib the code from glibc which
avoids division for small allocations:

/* size_t is unsigned so the behavior on overflow is defined. */
bytes = n * elem_size;
#define HALF_INTERNAL_SIZE_T \
(((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0)) {
if (elem_size != 0 && bytes / elem_size != n) {
MALLOC_FAILURE_ACTION;
return 0;
}
}

-dean