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