4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * Versions of malloc and friends that check their results, and never return
8 * failure (they call errx if they encounter an error).
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
34 errx(1, "xmalloc: zero size");
37 errx(1, "xmalloc: allocating %zu bytes: %s",
38 size, strerror(errno));
43 xcalloc(size_t nmemb, size_t size)
47 if (size == 0 || nmemb == 0)
48 errx(1, "xcalloc: zero size");
49 ptr = calloc(nmemb, size);
51 errx(1, "xcalloc: allocating %zu * %zu bytes: %s",
52 nmemb, size, strerror(errno));
57 xrealloc(void *ptr, size_t size)
59 return xreallocarray(ptr, 1, size);
63 xreallocarray(void *ptr, size_t nmemb, size_t size)
67 if (nmemb == 0 || size == 0)
68 errx(1, "xreallocarray: zero size");
69 new_ptr = reallocarray(ptr, nmemb, size);
71 errx(1, "xreallocarray: allocating %zu * %zu bytes: %s",
72 nmemb, size, strerror(errno));
77 xrecallocarray(void *ptr, size_t oldnmemb, size_t nmemb, size_t size)
81 if (nmemb == 0 || size == 0)
82 errx(1, "xrecallocarray: zero size");
83 new_ptr = recallocarray(ptr, oldnmemb, nmemb, size);
85 errx(1, "xrecallocarray: allocating %zu * %zu bytes: %s",
86 nmemb, size, strerror(errno));
91 xstrdup(const char *str)
95 if ((cp = strdup(str)) == NULL)
96 errx(1, "xstrdup: %s", strerror(errno));
101 xstrndup(const char *str, size_t maxlen)
105 if ((cp = strndup(str, maxlen)) == NULL)
106 errx(1, "xstrndup: %s", strerror(errno));
111 xasprintf(char **ret, const char *fmt, ...)
117 i = xvasprintf(ret, fmt, ap);
124 xvasprintf(char **ret, const char *fmt, va_list ap)
128 i = vasprintf(ret, fmt, ap);
131 errx(1, "xasprintf: %s", strerror(errno));
137 xsnprintf(char *str, size_t len, const char *fmt, ...)
143 i = xvsnprintf(str, len, fmt, ap);
150 xvsnprintf(char *str, size_t len, const char *fmt, va_list ap)
155 errx(1, "xsnprintf: len > INT_MAX");
157 i = vsnprintf(str, len, fmt, ap);
159 if (i < 0 || i >= (int)len)
160 errx(1, "xsnprintf: overflow");