xref: /openbsd/usr.bin/ctfconv/xmalloc.c (revision 4cfece93)
1 /* $OpenBSD: xmalloc.c,v 1.1 2017/08/11 14:21:24 mpi Exp $ */
2 
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * Versions of malloc and friends that check their results, and never return
8  * failure (they call fatalx if they encounter an error).
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  */
16 
17 #include <err.h>
18 #include <limits.h>
19 #include <stdarg.h>
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 
25 #include "xmalloc.h"
26 
27 void *
28 xmalloc(size_t size)
29 {
30 	void *ptr;
31 
32 	if (size == 0)
33 		errx(1, "xmalloc: zero size");
34 	ptr = malloc(size);
35 	if (ptr == NULL)
36 		err(1, "xmalloc: allocating %zu bytes", size);
37 	return ptr;
38 }
39 
40 void *
41 xcalloc(size_t nmemb, size_t size)
42 {
43 	void *ptr;
44 
45 	if (size == 0 || nmemb == 0)
46 		errx(1, "xcalloc: zero size");
47 	ptr = calloc(nmemb, size);
48 	if (ptr == NULL)
49 		err(1, "xcalloc: allocating %zu * %zu bytes",
50 		    nmemb, size);
51 	return ptr;
52 }
53 
54 void *
55 xrealloc(void *ptr, size_t size)
56 {
57 	return xreallocarray(ptr, 1, size);
58 }
59 
60 void *
61 xreallocarray(void *ptr, size_t nmemb, size_t size)
62 {
63 	void *new_ptr;
64 
65 	if (nmemb == 0 || size == 0)
66 		errx(1, "xreallocarray: zero size");
67 	new_ptr = reallocarray(ptr, nmemb, size);
68 	if (new_ptr == NULL)
69 		err(1, "xreallocarray: allocating %zu * %zu bytes",
70 		    nmemb, size);
71 	return new_ptr;
72 }
73 
74 char *
75 xstrdup(const char *str)
76 {
77 	char *cp;
78 
79 	if ((cp = strdup(str)) == NULL)
80 		err(1, "xstrdup");
81 	return cp;
82 }
83