[commit: ghc] master: stgMallocBytes: Tolerate malloc(0) returning a NULL ptr (1934f7f)

git at git.haskell.org git at git.haskell.org
Mon Mar 21 20:43:03 UTC 2016


Repository : ssh://git@git.haskell.org/ghc

On branch  : master
Link       : http://ghc.haskell.org/trac/ghc/changeset/1934f7f1066423a6b35b1f17bf63d40c92681d31/ghc

>---------------------------------------------------------------

commit 1934f7f1066423a6b35b1f17bf63d40c92681d31
Author: Herbert Valerio Riedel <hvr at gnu.org>
Date:   Mon Mar 21 21:40:23 2016 +0100

    stgMallocBytes: Tolerate malloc(0) returning a NULL ptr
    
    This is valid behaviour for `malloc()` according to ISO C99 and POSIX,
    and there's at least one operating system (AIX) which actually does return
    NULL for 0-sized allocations.
    
    The `createAdjustor()` routine is currently the only known use-site of
    `stgMallocBytes` which may call `stgMallocBytes()` requesting a 0-size
    allocation.
    
    Reviewed By: bgamari, austin
    
    Differential Revision: https://phabricator.haskell.org/D2022


>---------------------------------------------------------------

1934f7f1066423a6b35b1f17bf63d40c92681d31
 rts/RtsUtils.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/rts/RtsUtils.c b/rts/RtsUtils.c
index 72e19a0..a36532c 100644
--- a/rts/RtsUtils.c
+++ b/rts/RtsUtils.c
@@ -64,6 +64,19 @@ stgMallocBytes (int n, char *msg)
 
     n2 = (size_t) n;
     if ((space = (char *) malloc(n2)) == NULL) {
+      /* Quoting POSIX.1-2008 (which says more or less the same as ISO C99):
+       *
+       *   "Upon successful completion with size not equal to 0, malloc() shall
+       *   return a pointer to the allocated space. If size is 0, either a null
+       *   pointer or a unique pointer that can be successfully passed to free()
+       *   shall be returned. Otherwise, it shall return a null pointer and set
+       *   errno to indicate the error."
+       *
+       * Consequently, a NULL pointer being returned by `malloc()` for a 0-size
+       * allocation is *not* to be considered an error.
+       */
+      if (n == 0) return NULL;
+
       /* don't fflush(stdout); WORKAROUND bug in Linux glibc */
       rtsConfig.mallocFailHook((W_) n, msg); /*msg*/
       stg_exit(EXIT_INTERNAL_ERROR);



More information about the ghc-commits mailing list