Speedup calloc size overflow check by preventing division if small values
authorHans Boehm <Hans.Boehm@hp.com>
Thu, 15 Mar 2012 17:09:05 +0000 (21:09 +0400)
committerIvan Maidanski <ivmai@mail.ru>
Thu, 15 Mar 2012 17:09:05 +0000 (21:09 +0400)
* malloc.c (GC_SQRT_SIZE_MAX): New macro.
* malloc.c (calloc): Add fast initial size overflow check to avoid
integer division for reasonably small values passed.

malloc.c

index cb49a5c..c9b9eb6 100644 (file)
--- a/malloc.c
+++ b/malloc.c
@@ -381,9 +381,12 @@ void * malloc(size_t lb)
 # define GC_SIZE_MAX (~(size_t)0)
 #endif
 
+#define GC_SQRT_SIZE_MAX ((1U << (WORDSZ / 2)) - 1)
+
 void * calloc(size_t n, size_t lb)
 {
-    if (lb && n > GC_SIZE_MAX / lb)
+    if ((lb | n) > GC_SQRT_SIZE_MAX /* fast initial test */
+        && lb && n > GC_SIZE_MAX / lb)
       return NULL;
 #   if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
         /* libpthread allocated some memory that is only pointed to by  */