* xmalloc.c (HAVE_GNU_CALLOC): New constant.
authorPaul Eggert <eggert@cs.ucla.edu>
Wed, 22 Jun 2005 07:12:04 +0000 (07:12 +0000)
committerPaul Eggert <eggert@cs.ucla.edu>
Wed, 22 Jun 2005 07:12:04 +0000 (07:12 +0000)
(xcalloc): Use it to avoid needless tests.

lib/ChangeLog
lib/xmalloc.c

index 9912962563a88321d7f81e731e53b9aa6fb5bad4..cffd88ee0531f189d01b922a6c0cad4486b97e88 100644 (file)
@@ -1,3 +1,9 @@
+2005-06-22  Paul Eggert  <eggert@cs.ucla.edu>
+
+       * xmalloc.c (HAVE_GNU_CALLOC): New constant.
+       (xcalloc): Use it to avoid needless tests.
+       Problem reported by Jim Meyering.
+
 2005-06-16  Jim Meyering  <jim@meyering.net>
 
        * calloc.c (rpl_calloc): Allocate a 1-byte buffer (not 1xS or Nx1)
index c1632b96de5ebed31ecbd3a096b6e0822d9d6f63..6977703b8024c87c811d9e711ebe5ae08d3625c6 100644 (file)
@@ -1,7 +1,7 @@
 /* xmalloc.c -- malloc with out of memory checking
 
    Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
-   1999, 2000, 2002, 2003, 2004 Free Software Foundation, Inc.
+   1999, 2000, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
 # define SIZE_MAX ((size_t) -1)
 #endif
 
+/* 1 if calloc is known to be compatible with GNU calloc.  This
+   matters if we are not also using the calloc module, which defines
+   HAVE_CALLOC and supports the GNU API even on non-GNU platforms.  */
+#if defined HAVE_CALLOC || defined __GLIBC__
+enum { HAVE_GNU_CALLOC = 1 };
+#else
+enum { HAVE_GNU_CALLOC = 0 };
+#endif
+
 /* Allocate an array of N objects, each with S bytes of memory,
    dynamically, with error checking.  S must be nonzero.  */
 
@@ -204,8 +213,11 @@ xcalloc (size_t n, size_t s)
 {
   void *p;
   /* Test for overflow, since some calloc implementations don't have
-     proper overflow checks.  */
-  if (xalloc_oversized (n, s) || (! (p = calloc (n, s)) && n != 0))
+     proper overflow checks.  But omit overflow and size-zero tests if
+     HAVE_GNU_CALLOC, since GNU calloc catches overflow and never
+     returns NULL if successful.  */
+  if ((! HAVE_GNU_CALLOC && xalloc_oversized (n, s))
+      || (! (p = calloc (n, s)) && (HAVE_GNU_CALLOC || n != 0)))
     xalloc_die ();
   return p;
 }