xref: /openbsd-src/usr.bin/rcs/xmalloc.c (revision 91f110e064cd7c194e59e019b83bb7496c1c84d4)
1 /* $OpenBSD: xmalloc.c,v 1.4 2009/06/07 08:39:13 ray 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 <limits.h>
18 #include <stdarg.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 	if (size == 0)
31 		errx(1, "xmalloc: zero size");
32 	ptr = malloc(size);
33 	if (ptr == NULL)
34 		errx(1,
35 		    "xmalloc: out of memory (allocating %lu bytes)",
36 		    (u_long) 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 	if (SIZE_MAX / nmemb < size)
48 		errx(1, "xcalloc: nmemb * size > SIZE_MAX");
49 	ptr = calloc(nmemb, size);
50 	if (ptr == NULL)
51 		errx(1, "xcalloc: out of memory (allocating %lu bytes)",
52 		    (u_long)(size * nmemb));
53 	return ptr;
54 }
55 
56 void *
57 xrealloc(void *ptr, size_t nmemb, size_t size)
58 {
59 	void *new_ptr;
60 	size_t new_size = nmemb * size;
61 
62 	if (new_size == 0)
63 		errx(1, "xrealloc: zero size");
64 	if (SIZE_MAX / nmemb < size)
65 		errx(1, "xrealloc: nmemb * size > SIZE_MAX");
66 	if (ptr == NULL)
67 		new_ptr = malloc(new_size);
68 	else
69 		new_ptr = realloc(ptr, new_size);
70 	if (new_ptr == NULL)
71 		errx(1, "xrealloc: out of memory (new_size %lu bytes)",
72 		    (u_long) new_size);
73 	return new_ptr;
74 }
75 
76 void
77 xfree(void *ptr)
78 {
79 	if (ptr == NULL)
80 		errx(1, "xfree: NULL pointer given as argument");
81 	free(ptr);
82 }
83 
84 char *
85 xstrdup(const char *str)
86 {
87 	size_t len;
88 	char *cp;
89 
90 	len = strlen(str) + 1;
91 	cp = xmalloc(len);
92 	if (strlcpy(cp, str, len) >= len)
93 		errx(1, "xstrdup: string truncated");
94 	return cp;
95 }
96 
97 int
98 xasprintf(char **ret, const char *fmt, ...)
99 {
100 	va_list ap;
101 	int i;
102 
103 	va_start(ap, fmt);
104 	i = vasprintf(ret, fmt, ap);
105 	va_end(ap);
106 
107 	if (i < 0 || *ret == NULL)
108 		errx(1, "xasprintf: could not allocate memory");
109 
110 	return (i);
111 }
112