1 /* $OpenBSD: xmalloc.c,v 1.29 2014/01/04 17:50:55 tedu 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".
18 #include <sys/param.h>
33 fatal("xmalloc: zero size");
36 fatal("xmalloc: out of memory (allocating %zu bytes)", size
);
41 xcalloc(size_t nmemb
, size_t size
)
45 if (size
== 0 || nmemb
== 0)
46 fatal("xcalloc: zero size");
47 if (SIZE_T_MAX
/ nmemb
< size
)
48 fatal("xcalloc: nmemb * size > SIZE_T_MAX");
49 ptr
= calloc(nmemb
, size
);
51 fatal("xcalloc: out of memory (allocating %zu bytes)",
57 xrealloc(void *ptr
, size_t nmemb
, size_t size
)
60 size_t new_size
= nmemb
* size
;
63 fatal("xrealloc: zero size");
64 if (SIZE_T_MAX
/ nmemb
< size
)
65 fatal("xrealloc: nmemb * size > SIZE_T_MAX");
67 new_ptr
= malloc(new_size
);
69 new_ptr
= realloc(ptr
, new_size
);
71 fatal("xrealloc: out of memory (new_size %zu bytes)",
77 xstrdup(const char *str
)
82 len
= strlen(str
) + 1;
84 strlcpy(cp
, str
, len
);
89 xasprintf(char **ret
, const char *fmt
, ...)
95 i
= vasprintf(ret
, fmt
, ap
);
98 if (i
< 0 || *ret
== NULL
)
99 fatal("xasprintf: could not allocate memory");