1 /* $OpenBSD: xmalloc.c,v 1.10 2019/06/28 05:44:09 deraadt Exp $ */
2 /*
3 * Author: Tatu Ylonen <[email protected]>
4 * Copyright (c) 1995 Tatu Ylonen <[email protected]>, 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 */
15
16 #include <sys/cdefs.h>
17 #include <err.h>
18 #include <stdarg.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23
24 #include "xmalloc.h"
25
26 void *
xmalloc(size_t size)27 xmalloc(size_t size)
28 {
29 void *ptr;
30
31 if (size == 0)
32 errx(2, "xmalloc: zero size");
33 ptr = malloc(size);
34 if (ptr == NULL)
35 err(2, "xmalloc: allocating %zu bytes", size);
36 return ptr;
37 }
38
39 void *
xcalloc(size_t nmemb,size_t size)40 xcalloc(size_t nmemb, size_t size)
41 {
42 void *ptr;
43
44 ptr = calloc(nmemb, size);
45 if (ptr == NULL)
46 err(2, "xcalloc: allocating %zu * %zu bytes", nmemb, size);
47 return ptr;
48 }
49
50 void *
xreallocarray(void * ptr,size_t nmemb,size_t size)51 xreallocarray(void *ptr, size_t nmemb, size_t size)
52 {
53 void *new_ptr;
54
55 new_ptr = reallocarray(ptr, nmemb, size);
56 if (new_ptr == NULL)
57 err(2, "xreallocarray: allocating %zu * %zu bytes",
58 nmemb, size);
59 return new_ptr;
60 }
61
62 char *
xstrdup(const char * str)63 xstrdup(const char *str)
64 {
65 char *cp;
66
67 if ((cp = strdup(str)) == NULL)
68 err(2, "xstrdup");
69 return cp;
70 }
71
72 int
xasprintf(char ** ret,const char * fmt,...)73 xasprintf(char **ret, const char *fmt, ...)
74 {
75 va_list ap;
76 int i;
77
78 va_start(ap, fmt);
79 i = vasprintf(ret, fmt, ap);
80 va_end(ap);
81
82 if (i == -1)
83 err(2, "xasprintf");
84
85 return i;
86 }
87