1 /* $OpenBSD: xmalloc.c,v 1.22 2006/07/10 16:37:36 stevesk 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".
29 fatal("xmalloc: zero size");
32 fatal("xmalloc: out of memory (allocating %lu bytes)", (u_long
) size
);
37 xcalloc(size_t nmemb
, size_t size
)
41 if (size
== 0 || nmemb
== 0)
42 fatal("xcalloc: zero size");
43 if (SIZE_T_MAX
/ nmemb
< size
)
44 fatal("xcalloc: nmemb * size > SIZE_T_MAX");
45 ptr
= calloc(nmemb
, size
);
47 fatal("xcalloc: out of memory (allocating %lu bytes)",
48 (u_long
)(size
* nmemb
));
53 xrealloc(void *ptr
, size_t nmemb
, size_t size
)
56 size_t new_size
= nmemb
* size
;
59 fatal("xrealloc: zero size");
60 if (SIZE_T_MAX
/ nmemb
< size
)
61 fatal("xrealloc: nmemb * size > SIZE_T_MAX");
63 new_ptr
= malloc(new_size
);
65 new_ptr
= realloc(ptr
, new_size
);
67 fatal("xrealloc: out of memory (new_size %lu bytes)",
76 fatal("xfree: NULL pointer given as argument");
81 xstrdup(const char *str
)
86 len
= strlen(str
) + 1;
88 strlcpy(cp
, str
, len
);
93 xasprintf(char **ret
, const char *fmt
, ...)
99 i
= vasprintf(ret
, fmt
, ap
);
102 if (i
< 0 || *ret
== NULL
)
103 fatal("xasprintf: could not allocate memory");