]> diplodocus.org Git - nmh/commitdiff
Tweak mh_xrealloc(); print size on error, follow POSIX.
authorRalph Corderoy <ralph@inputplus.co.uk>
Sun, 16 Oct 2016 17:08:29 +0000 (18:08 +0100)
committerRalph Corderoy <ralph@inputplus.co.uk>
Sun, 16 Oct 2016 17:08:29 +0000 (18:08 +0100)
Using `%zu' for the size_t value.  That might be a problem on older
platforms, but we'll see.  If asked for zero bytes then free an existing
pointer, only passing it to free(3) if it's non-NULL, and then allocate
a byte so a unique pointer is returned.

h/utils.h
sbr/utils.c

index 3a42819..20ebd2c 100644 (file)
--- a/h/utils.h
+++ b/h/utils.h
@@ -6,7 +6,9 @@
 /* Call malloc(3), exiting on NULL return. */
 void *mh_xmalloc(size_t);
 
+/* Call realloc(3), exiting on NULL return. */
 void *mh_xrealloc(void *, size_t);
+
 void *mh_xcalloc(size_t, size_t);
 char *pwd(void);
 char *add(const char *, char *);
index d322890..83c3217 100644 (file)
@@ -39,26 +39,26 @@ void *mh_xmalloc(size_t size)
     return p;
 }
 
-/*
- * Safely call realloc
- */
-void *
-mh_xrealloc(void *ptr, size_t size)
+/* Call realloc(3), exiting on NULL return. */
+void *mh_xrealloc(void *ptr, size_t size)
 {
-    void *memory;
+    void *new;
 
-    /* Some non-POSIX realloc()s don't cope with realloc(NULL,sz) */
+    /* Copy POSIX behaviour, coping with non-POSIX systems. */
+    if (size == 0) {
+        if (ptr) {
+            free(ptr);
+        }
+        return mh_xmalloc(1); /* Get a unique pointer. */
+    }
     if (!ptr)
         return mh_xmalloc(size);
 
-    if (size == 0)
-        adios(NULL, "Tried to realloc 0 bytes");
-
-    memory = realloc(ptr, size);
-    if (!memory)
-        adios(NULL, "Realloc failed");
+    new = realloc(ptr, size);
+    if (!new)
+        adios(NULL, "realloc failed, size wanted: %zu", size);
 
-    return memory;
+    return new;
 }
 
 /*