]> git.tuebingen.mpg.de Git - paraslash.git/blobdiff - string.c
string: Introduce arr_realloc() and check for integer overflow.
[paraslash.git] / string.c
index bbc322eb52dd2c529bd0622e84b2f2eeabe290fb..f98b199b569856d7e6df624eaf6cb1cd7ff5802e 100644 (file)
--- a/string.c
+++ b/string.c
 #include "string.h"
 #include "error.h"
 
+/**
+ * Reallocate an array, abort on failure or bugs.
+ *
+ * \param ptr Pointer to the memory block, may be NULL.
+ * \param nmemb Number of elements.
+ * \param size The size of one element in bytes.
+ *
+ * A wrapper for realloc(3) which aborts on invalid arguments or integer
+ * overflow. The wrapper also terminates the current process on allocation
+ * errors, so the caller does not need to check for failure.
+ *
+ * \return A pointer to newly allocated memory which is suitably aligned for
+ * any kind of variable and may be different from ptr.
+ *
+ * \sa realloc(3).
+ */
+__must_check void *arr_realloc(void *ptr, size_t nmemb, size_t size)
+{
+       size_t pr;
+
+       assert(size > 0);
+       assert(nmemb > 0);
+       assert(!__builtin_mul_overflow(nmemb, size, &pr));
+       assert(pr != 0);
+       ptr = realloc(ptr, pr);
+       assert(ptr);
+       return ptr;
+}
+
 /**
  * Paraslash's version of realloc().
  *
  */
 __must_check void *para_realloc(void *p, size_t size)
 {
-       /*
-        * No need to check for NULL pointers: If p is NULL, the call
-        * to realloc is equivalent to malloc(size)
-        */
-       assert(size);
-       if (!(p = realloc(p, size))) {
-               PARA_EMERG_LOG("realloc failed (size = %zu), aborting\n",
-                       size);
-               exit(EXIT_FAILURE);
-       }
-       return p;
+       return arr_realloc(p, 1, size);
 }
 
 /**
@@ -734,7 +753,7 @@ static int create_argv_offset(int offset, const char *buf, const char *delim,
                        goto err;
                if (!ret)
                        break;
-               argv = para_realloc(argv, (i + 2) * sizeof(char*));
+               argv = arr_realloc(argv, i + 2, sizeof(char*));
                argv[i] = word;
        }
        argv[i] = NULL;