chiark / gitweb /
realloc: Provide safe_realloc_ary
authorIan Jackson <ijackson@chiark.greenend.org.uk>
Sat, 20 Sep 2014 13:10:28 +0000 (14:10 +0100)
committerIan Jackson <ijackson@chiark.greenend.org.uk>
Mon, 6 Oct 2014 22:09:56 +0000 (23:09 +0100)
Also, make it OK to call safe_malloc(0).

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
secnet.h
util.c

index 0e2e1f7819057a17b8911a7c1647cb0cd70508de..e79352becb0cd853773b109f9c087e85506ef8fa 100644 (file)
--- a/secnet.h
+++ b/secnet.h
@@ -165,6 +165,8 @@ extern uint32_t string_list_to_word(list_t *l, struct flagstr *f,
 extern char *safe_strdup(const char *string, const char *message);
 extern void *safe_malloc(size_t size, const char *message);
 extern void *safe_malloc_ary(size_t size, size_t count, const char *message);
+extern void *safe_realloc_ary(void *p, size_t size, size_t count,
+                             const char *message);
 
 void setcloexec(int fd); /* cannot fail */
 void pipe_cloexec(int fd[2]); /* pipe(), setcloexec() twice; cannot fail */
diff --git a/util.c b/util.c
index 9c8abb3393353cf08322d4292f9e0e4d0c71ccfd..e34336c77e4cc171f69555ad87b00d1e6f762e5d 100644 (file)
--- a/util.c
+++ b/util.c
@@ -71,17 +71,30 @@ char *safe_strdup(const char *s, const char *message)
 void *safe_malloc(size_t size, const char *message)
 {
     void *r;
+    if (!size)
+       return 0;
     r=malloc(size);
     if (!r) {
        fatal_perror("%s",message);
     }
     return r;
 }
-void *safe_malloc_ary(size_t size, size_t count, const char *message) {
+void *safe_realloc_ary(void *p, size_t size, size_t count,
+                      const char *message) {
     if (count >= INT_MAX/size) {
        fatal("array allocation overflow: %s", message);
     }
-    return safe_malloc(size*count, message);
+    assert(size && count);
+    p = realloc(p, size*count);
+    if (!p)
+       fatal_perror("%s", message);
+    return p;
+}
+
+void *safe_malloc_ary(size_t size, size_t count, const char *message) {
+    if (!size || !count)
+       return 0;
+    return safe_realloc_ary(0,size,count,message);
 }
 
 /* Convert a buffer into its MP_INT representation */