[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: xmalloc.c's xcalloc performs unnecessary test for N*S overflow

From: Paul Eggert
Subject: Re: xmalloc.c's xcalloc performs unnecessary test for N*S overflow
Date: Fri, 17 Jun 2005 10:42:26 -0700
User-agent: Gnus/5.1006 (Gnus v5.10.6) Emacs/21.4 (gnu/linux)

Jim Meyering <address@hidden> writes:

> This makes me think it'd be worthwhile to support a new section in
> the modules file listing `Recommended' modules.

Yes, that would be nice.  It's been suggested before but nobody has
had the time yet to do it.  gnulib-tool might bring in recommended
modules automatically on request, for example.

> But why reuse the HAVE_CALLOC symbol at all?
> It's name isn't really accurate in this context.
> How about this instead:

Yes, that would be better (and thanks for catching the bug -- I did
say my patch was untested :-).  Though I think it'd be better to
reverse the sense and call it "HAVE_GNU_CALLOC" or something like
that.  How about the following (also untested) patch?

2005-06-17  Paul Eggert  <address@hidden>

        * xmalloc (HAVE_GNU_CALLOC): New macro.
        (xcalloc): Omit needless tests if ! HAVE_GNU_CALLOC.

--- xmalloc.c   2005-05-13 23:03:58 -0700
+++ /tmp/xmalloc.c      2005-06-17 10:28:06 -0700
@@ -30,6 +30,15 @@
 # define SIZE_MAX ((size_t) -1)
+/* 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.  */
+# define HAVE_GNU_CALLOC 1
+# define HAVE_GNU_CALLOC 0
 /* 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;

reply via email to

[Prev in Thread] Current Thread [Next in Thread]