]> git.deb.at Git - pkg/abook.git/blobdiff - xmalloc.c
build system: updating gnuconfig files to 2013-06-10
[pkg/abook.git] / xmalloc.c
index 086f3fbb69ed9b5fe351a9078af9e75d29abf80a..3a34e1ce187a864a029c434a221a4c4fd2fbe0db 100644 (file)
--- a/xmalloc.c
+++ b/xmalloc.c
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include "gettext.h"
+#include "xmalloc.h"
 
 static void
 xmalloc_default_error_handler(int err)
 {
-       fprintf(stderr, "Memory allocation failure: %s\n", strerror(err));
+       fprintf(stderr, _("Memory allocation failure: %s\n"), strerror(err));
        exit(EXIT_FAILURE);
 }
 
@@ -78,22 +80,6 @@ xmalloc0(size_t size)
        return p;
 }
 
-void *
-xrealloc(void *ptr, size_t size)
-{
-       if((ptr = realloc(ptr, size)) == NULL)
-               (*xmalloc_handle_error)(errno);
-
-       return ptr;
-}
-
-void
-xfree(void *ptr)
-{
-       free(ptr);
-       ptr = NULL;
-}
-
 static void *
 _xmalloc_inc(size_t size, size_t inc, int zero)
 {
@@ -122,3 +108,62 @@ xmalloc0_inc(size_t size, size_t inc)
        return _xmalloc_inc(size, inc, 1);
 }
 
+void *
+xrealloc(void *ptr, size_t size)
+{
+       if((ptr = realloc(ptr, size)) == NULL)
+               (*xmalloc_handle_error)(errno);
+
+       return ptr;
+}
+
+void *
+xrealloc_inc(void *ptr, size_t size, size_t inc)
+{
+       size_t total_size = size + inc;
+
+       /*
+        * check if the calculation overflowed
+        */
+       if(total_size < size) {
+               (*xmalloc_handle_error)(EINVAL);
+               return NULL;
+       }
+
+       if((ptr = realloc(ptr, total_size)) == NULL)
+               (*xmalloc_handle_error)(errno);
+
+       return ptr;
+}
+
+char *
+xstrdup(const char *s)
+{
+       size_t len = strlen(s);
+       void *new;
+
+       new = xmalloc_inc(len, 1);
+       if(new == NULL)
+               return NULL;
+
+       return (char *)memcpy(new, s, len + 1);
+}
+
+char *
+xstrndup(const char *s, size_t len)
+{
+       char *new;
+       size_t n = strlen(s);
+
+       if(n > len)
+               n = len;
+
+       new = xmalloc_inc(n, 1);
+       if(new == NULL)
+               return NULL;
+
+       memcpy(new, s, n);
+       new[n] = '\0';
+
+       return new;
+}