1 /* $OpenBSD: xmalloc.c,v 1.32 2015/04/24 01:36:01 deraadt Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Versions of malloc and friends that check their results, and never return
7 * failure (they call fatal if they encounter an error).
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
35 fatal("xmalloc: zero size");
38 fatal("xmalloc: out of memory (allocating %zu bytes)", size);
43 xcalloc(size_t nmemb, size_t size)
47 if (size == 0 || nmemb == 0)
48 fatal("xcalloc: zero size");
49 if (SIZE_MAX / nmemb < size)
50 fatal("xcalloc: nmemb * size > SIZE_MAX");
51 ptr = calloc(nmemb, size);
53 fatal("xcalloc: out of memory (allocating %zu bytes)",
59 xreallocarray(void *ptr, size_t nmemb, size_t size)
63 new_ptr = reallocarray(ptr, nmemb, size);
65 fatal("xreallocarray: out of memory (%zu elements of %zu bytes)",
71 xstrdup(const char *str)
76 len = strlen(str) + 1;
78 strlcpy(cp, str, len);
83 xasprintf(char **ret, const char *fmt, ...)
89 i = vasprintf(ret, fmt, ap);
92 if (i < 0 || *ret == NULL)
93 fatal("xasprintf: could not allocate memory");