summaryrefslogtreecommitdiff
path: root/xalloc.h
diff options
context:
space:
mode:
Diffstat (limited to 'xalloc.h')
-rw-r--r--xalloc.h34
1 files changed, 30 insertions, 4 deletions
diff --git a/xalloc.h b/xalloc.h
index 5810fc55..0d169cf9 100644
--- a/xalloc.h
+++ b/xalloc.h
@@ -136,6 +136,8 @@ xnmalloc (size_t n, size_t s)
#ifdef GAWK
#include <errno.h>
+extern void r_fatal(const char *msg, ...) ATTRIBUTE_NORETURN ;
+
/* Allocate an array of N objects, each with S bytes of memory,
dynamically, with error checking. S must be nonzero.
Clear the contents afterwards. */
@@ -165,10 +167,34 @@ xrealloc(void *p, size_t size)
void
xalloc_die (void)
{
- extern void r_fatal(const char *msg, ...) ATTRIBUTE_NORETURN ;
-
r_fatal(_("xalloc: malloc failed: %s"), strerror(errno));
}
+
+/* Clone an object P of size S, with error checking. There's no need
+ for xnmemdup (P, N, S), since xmemdup (P, N * S) works without any
+ need for an arithmetic overflow check. */
+
+void *
+xmemdup (void const *p, size_t s)
+{
+ return memcpy (xmalloc (s), p, s);
+}
+
+/* xstrdup --- strdup and die if fails */
+char *xstrdup(const char *s)
+{
+ char *p;
+ int l;
+
+ if (s == NULL)
+ r_fatal(_("xstrdup: null parameter"));
+
+ l = strlen(s);
+ p = xmemdup(s, l + 1);
+ p[l] = '\0';
+
+ return p;
+}
#endif
/* Change the size of an allocated block of memory P to an array of N
@@ -250,7 +276,7 @@ x2nrealloc (void *p, size_t *pn, size_t s)
requests, when the invoking code specifies an old size of
zero. 64 bytes is the largest "small" request for the
GNU C library malloc. */
- enum { DEFAULT_MXFAST = 64 };
+ enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
n = DEFAULT_MXFAST / s;
n += !n;
@@ -264,7 +290,7 @@ x2nrealloc (void *p, size_t *pn, size_t s)
worth the trouble. */
if ((size_t) -1 / 3 * 2 / s <= n)
xalloc_die ();
- n += (n + 1) / 2;
+ n += n / 2 + 1;
}
*pn = n;