Blob


1 /* $OpenBSD: xmalloc.c,v 1.4 2019/06/28 05:44:09 deraadt Exp $ */
2 /*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * Versions of malloc and friends that check their results, and never return
7 * failure (they call fatal if they encounter an error).
8 *
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".
14 */
16 #include "config.h"
18 #include <stdarg.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <syslog.h>
25 #include "log.h"
26 #include "xmalloc.h"
28 void *
29 xmalloc(size_t size)
30 {
31 void *ptr;
33 if (size == 0)
34 fatal("xmalloc: zero size");
35 ptr = malloc(size);
36 if (ptr == NULL)
37 fatal("xmalloc: allocating %zu bytes", size);
38 return ptr;
39 }
41 void *
42 xcalloc(size_t nmemb, size_t size)
43 {
44 void *ptr;
46 if (size == 0 || nmemb == 0)
47 fatal("xcalloc: zero size");
48 ptr = calloc(nmemb, size);
49 if (ptr == NULL)
50 fatal("xcalloc: allocating %zu * %zu bytes", nmemb, size);
51 return ptr;
52 }
54 void *
55 xreallocarray(void *ptr, size_t nmemb, size_t size)
56 {
57 void *new_ptr;
59 new_ptr = reallocarray(ptr, nmemb, size);
60 if (new_ptr == NULL)
61 fatal("xreallocarray: allocating %zu * %zu bytes",
62 nmemb, size);
63 return new_ptr;
64 }
66 void *
67 xrecallocarray(void *ptr, size_t oldnmemb, size_t nmemb, size_t size)
68 {
69 void *new_ptr;
71 new_ptr = recallocarray(ptr, oldnmemb, nmemb, size);
72 if (new_ptr == NULL)
73 fatal("xrecallocarray: allocating %zu * %zu bytes",
74 nmemb, size);
75 return new_ptr;
76 }
78 char *
79 xstrdup(const char *str)
80 {
81 char *cp;
83 if ((cp = strdup(str)) == NULL)
84 fatal("xstrdup");
85 return cp;
86 }
88 int
89 xasprintf(char **ret, const char *fmt, ...)
90 {
91 va_list ap;
92 int i;
94 va_start(ap, fmt);
95 i = vasprintf(ret, fmt, ap);
96 va_end(ap);
98 if (i == -1)
99 fatal("xasprintf");
101 return i;