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 fatalx 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".
24 #include "got_compat.h"
34 fprintf(stderr
,"xmalloc: zero size");
39 fprintf(stderr
, "xmalloc: allocating %zu bytes: %s",
40 size
, strerror(errno
));
47 xcalloc(size_t nmemb
, size_t size
)
51 if (size
== 0 || nmemb
== 0)
52 fprintf(stderr
,"xcalloc: zero size");
53 ptr
= calloc(nmemb
, size
);
55 fprintf(stderr
, "xcalloc: allocating %zu * %zu bytes: %s",
56 nmemb
, size
, strerror(errno
));
63 xrealloc(void *ptr
, size_t size
)
65 return xreallocarray(ptr
, 1, size
);
69 xreallocarray(void *ptr
, size_t nmemb
, size_t size
)
73 if (nmemb
== 0 || size
== 0) {
74 fprintf(stderr
, "xreallocarray: zero size");
77 new_ptr
= reallocarray(ptr
, nmemb
, size
);
78 if (new_ptr
== NULL
) {
79 fprintf(stderr
, "xreallocarray: allocating %zu * %zu bytes: %s",
80 nmemb
, size
, strerror(errno
));
87 xrecallocarray(void *ptr
, size_t oldnmemb
, size_t nmemb
, size_t size
)
91 if (nmemb
== 0 || size
== 0) {
92 fprintf(stderr
,"xrecallocarray: zero size");
95 new_ptr
= recallocarray(ptr
, oldnmemb
, nmemb
, size
);
96 if (new_ptr
== NULL
) {
97 fprintf(stderr
,"xrecallocarray: allocating %zu * %zu bytes: %s",
98 nmemb
, size
, strerror(errno
));
105 xstrdup(const char *str
)
109 if ((cp
= strdup(str
)) == NULL
) {
110 fprintf(stderr
,"xstrdup: %s", strerror(errno
));
117 xstrndup(const char *str
, size_t maxlen
)
121 if ((cp
= strndup(str
, maxlen
)) == NULL
) {
122 fprintf(stderr
,"xstrndup: %s", strerror(errno
));
129 xasprintf(char **ret
, const char *fmt
, ...)
135 i
= xvasprintf(ret
, fmt
, ap
);
142 xvasprintf(char **ret
, const char *fmt
, va_list ap
)
146 i
= vasprintf(ret
, fmt
, ap
);
149 fprintf(stderr
,"xasprintf: %s", strerror(errno
));
157 xsnprintf(char *str
, size_t len
, const char *fmt
, ...)
163 i
= xvsnprintf(str
, len
, fmt
, ap
);
170 xvsnprintf(char *str
, size_t len
, const char *fmt
, va_list ap
)
175 fprintf(stderr
,"xsnprintf: len > INT_MAX");
177 i
= vsnprintf(str
, len
, fmt
, ap
);
179 if (i
< 0 || i
>= (int)len
) {
180 fprintf(stderr
,"xsnprintf: overflow");