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