- djm@cvs.openbsd.org 2006/03/25 00:05:41
[auth-bsdauth.c auth-skey.c auth.c auth2-chall.c channels.c]
[clientloop.c deattack.c gss-genr.c kex.c key.c misc.c moduli.c]
[monitor.c monitor_wrap.c packet.c scard.c sftp-server.c ssh-agent.c]
[ssh-keyscan.c ssh.c sshconnect.c sshconnect2.c sshd.c uuencode.c]
[xmalloc.c xmalloc.h]
introduce xcalloc() and xasprintf() failure-checked allocations
functions and use them throughout openssh
xcalloc is particularly important because malloc(nmemb * size) is a
dangerous idiom (subject to integer overflow) and it is time for it
to die
feedback and ok deraadt@
diff --git a/xmalloc.c b/xmalloc.c
index 64e4398..6d56781 100644
--- a/xmalloc.c
+++ b/xmalloc.c
@@ -31,6 +31,22 @@
}
void *
+xcalloc(size_t nmemb, size_t size)
+{
+ void *ptr;
+
+ if (nmemb && size && SIZE_T_MAX / nmemb < size)
+ fatal("xcalloc: nmemb * size > SIZE_T_MAX");
+ if (size == 0 || nmemb == 0)
+ fatal("xcalloc: zero size");
+ ptr = calloc(nmemb, size);
+ if (ptr == NULL)
+ fatal("xcalloc: out of memory (allocating %lu bytes)",
+ (u_long)(size * nmemb));
+ return ptr;
+}
+
+void *
xrealloc(void *ptr, size_t new_size)
{
void *new_ptr;
@@ -65,3 +81,19 @@
strlcpy(cp, str, len);
return cp;
}
+
+int
+xasprintf(char **ret, const char *fmt, ...)
+{
+ va_list ap;
+ int i;
+
+ va_start(ap, fmt);
+ i = vasprintf(ret, fmt, ap);
+ va_end(ap);
+
+ if (i < 0 || *ret == NULL)
+ fatal("xasprintf: could not allocate memory");
+
+ return (i);
+}