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 <stdarg.h>
17 #include <stdint.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <syslog.h>
23 #include "log.h"
24 #include "xmalloc.h"
26 void *
27 xmalloc(size_t size)
28 {
29 void *ptr;
31 if (size == 0)
32 fatal("xmalloc: zero size");
33 ptr = malloc(size);
34 if (ptr == NULL)
35 fatal("xmalloc: allocating %zu bytes", size);
36 return ptr;
37 }
39 void *
40 xcalloc(size_t nmemb, size_t size)
41 {
42 void *ptr;
44 if (size == 0 || nmemb == 0)
45 fatal("xcalloc: zero size");
46 ptr = calloc(nmemb, size);
47 if (ptr == NULL)
48 fatal("xcalloc: allocating %zu * %zu bytes", nmemb, size);
49 return ptr;
50 }
52 void *
53 xreallocarray(void *ptr, size_t nmemb, size_t size)
54 {
55 void *new_ptr;
57 new_ptr = reallocarray(ptr, nmemb, size);
58 if (new_ptr == NULL)
59 fatal("xreallocarray: allocating %zu * %zu bytes",
60 nmemb, size);
61 return new_ptr;
62 }
64 void *
65 xrecallocarray(void *ptr, size_t oldnmemb, size_t nmemb, size_t size)
66 {
67 void *new_ptr;
69 new_ptr = recallocarray(ptr, oldnmemb, nmemb, size);
70 if (new_ptr == NULL)
71 fatal("xrecallocarray: allocating %zu * %zu bytes",
72 nmemb, size);
73 return new_ptr;
74 }
76 char *
77 xstrdup(const char *str)
78 {
79 char *cp;
81 if ((cp = strdup(str)) == NULL)
82 fatal("xstrdup");
83 return cp;
84 }
86 int
87 xasprintf(char **ret, const char *fmt, ...)
88 {
89 va_list ap;
90 int i;
92 va_start(ap, fmt);
93 i = vasprintf(ret, fmt, ap);
94 va_end(ap);
96 if (i == -1)
97 fatal("xasprintf");
99 return i;