Print this page
4922 all calloc() implementations should check for overflow

*** 22,49 **** /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ - #pragma ident "%Z%%M% %I% %E% SMI" - #include <stdlib.h> #include <string.h> /* * calloc - allocate and clear memory block */ void * calloc(size_t num, size_t size) { void *mp; ! num *= size; ! mp = malloc(num); if (mp == NULL) return (NULL); ! (void) memset(mp, 0, num); return (mp); } /*ARGSUSED*/ void --- 22,61 ---- /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include <stdlib.h> #include <string.h> + #include <errno.h> + /* * calloc - allocate and clear memory block */ void * calloc(size_t num, size_t size) { void *mp; + size_t total; + + if (num == 0 || size == 0) { + total = 0; + } else { + total = num * size; + + /* check for overflow */ + if ((total / num) != size) { + errno = ENOMEM; + return (NULL); + } + } ! mp = malloc(total); if (mp == NULL) return (NULL); ! (void) memset(mp, 0, total); return (mp); } /*ARGSUSED*/ void