2 /* $OpenBSD: xmalloc.c,v 1.27 2006/08/03 03:34:42 deraadt Exp $ */
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 fatal 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".
18 __RCSID("$NetBSD: xmalloc.c,v 1.8 2006/09/28 21:22:15 christos Exp $");
19 #include <sys/param.h>
34 fatal("xmalloc: zero size");
37 fatal("xmalloc: out of memory (allocating %lu bytes)", (u_long
) size
);
42 xcalloc(size_t nmemb
, size_t size
)
46 if (size
== 0 || nmemb
== 0)
47 fatal("xcalloc: zero size");
48 if (SIZE_T_MAX
/ nmemb
< size
)
49 fatal("xcalloc: nmemb * size > SIZE_T_MAX");
50 ptr
= calloc(nmemb
, size
);
52 fatal("xcalloc: out of memory (allocating %lu bytes)",
53 (u_long
)(size
* nmemb
));
58 xrealloc(void *ptr
, size_t nmemb
, size_t size
)
61 size_t new_size
= nmemb
* size
;
64 fatal("xrealloc: zero size");
65 if (SIZE_T_MAX
/ nmemb
< size
)
66 fatal("xrealloc: nmemb * size > SIZE_T_MAX");
68 new_ptr
= malloc(new_size
);
70 new_ptr
= realloc(ptr
, new_size
);
72 fatal("xrealloc: out of memory (new_size %lu bytes)",
81 fatal("xfree: NULL pointer given as argument");
86 xstrdup(const char *str
)
91 len
= strlen(str
) + 1;
93 strlcpy(cp
, str
, len
);
98 xasprintf(char **ret
, const char *fmt
, ...)
104 i
= vasprintf(ret
, fmt
, ap
);
107 if (i
< 0 || *ret
== NULL
)
108 fatal("xasprintf: could not allocate memory");