diff --git a/library/stdlib_calloc.c b/library/stdlib_calloc.c index be3e70e..af90d24 100644 --- a/library/stdlib_calloc.c +++ b/library/stdlib_calloc.c @@ -48,48 +48,47 @@ /****************************************************************************/ __static void * -__calloc(size_t num_elements,size_t element_size,const char * file,int line) +__calloc(size_t num_elements, size_t element_size, const char * file, int line) { void * result = NULL; size_t total_size; #ifdef __MEM_DEBUG { - /*__check_memory_allocations(file,line);*/ + __check_memory_allocations(file, line); } #endif /* __MEM_DEBUG */ - /* This might overflow. */ - total_size = num_elements * element_size; - - /* No arithmetic overflow? */ - if(total_size >= num_elements) - { - result = __malloc(total_size,file,line); - if(result != NULL) - memset(result,0,total_size); - else - SHOWMSG("memory allocation failure"); - } - /* Multiplying the number and size of elements overflows - * the size_t range. - */ - else + /* Check for overflow. */ + total_size = element_size * num_elements; + if (num_elements > 0 && element_size > 0 && element_size != (total_size / num_elements)) { D(("calloc(num_elements=%ld, element_size=%ld) overflow")); + goto out; } - return(result); + result = __malloc(total_size, file, line); + if (result == NULL) + { + SHOWMSG("memory allocation failure"); + goto out; + } + + memset(result, 0, total_size); + + out: + + return result; } /****************************************************************************/ void * -calloc(size_t num_elements,size_t element_size) +calloc(size_t num_elements, size_t element_size) { void * result; - result = __calloc(num_elements,element_size,NULL,0); + result = __calloc(num_elements, element_size, NULL, 0); return(result); }