+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;
+}