xref: /openbsd-src/usr.bin/ssh/xmalloc.c (revision 91f110e064cd7c194e59e019b83bb7496c1c84d4)
1 /* $OpenBSD: xmalloc.c,v 1.29 2014/01/04 17:50:55 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 <sys/param.h>
17 #include <stdarg.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 
22 #include "xmalloc.h"
23 #include "log.h"
24 
25 void *
26 xmalloc(size_t size)
27 {
28 	void *ptr;
29 
30 	if (size == 0)
31 		fatal("xmalloc: zero size");
32 	ptr = malloc(size);
33 	if (ptr == NULL)
34 		fatal("xmalloc: out of memory (allocating %zu bytes)", size);
35 	return ptr;
36 }
37 
38 void *
39 xcalloc(size_t nmemb, size_t size)
40 {
41 	void *ptr;
42 
43 	if (size == 0 || nmemb == 0)
44 		fatal("xcalloc: zero size");
45 	if (SIZE_T_MAX / nmemb < size)
46 		fatal("xcalloc: nmemb * size > SIZE_T_MAX");
47 	ptr = calloc(nmemb, size);
48 	if (ptr == NULL)
49 		fatal("xcalloc: out of memory (allocating %zu bytes)",
50 		    size * nmemb);
51 	return ptr;
52 }
53 
54 void *
55 xrealloc(void *ptr, size_t nmemb, size_t size)
56 {
57 	void *new_ptr;
58 	size_t new_size = nmemb * size;
59 
60 	if (new_size == 0)
61 		fatal("xrealloc: zero size");
62 	if (SIZE_T_MAX / nmemb < size)
63 		fatal("xrealloc: nmemb * size > SIZE_T_MAX");
64 	if (ptr == NULL)
65 		new_ptr = malloc(new_size);
66 	else
67 		new_ptr = realloc(ptr, new_size);
68 	if (new_ptr == NULL)
69 		fatal("xrealloc: out of memory (new_size %zu bytes)",
70 		    new_size);
71 	return new_ptr;
72 }
73 
74 char *
75 xstrdup(const char *str)
76 {
77 	size_t len;
78 	char *cp;
79 
80 	len = strlen(str) + 1;
81 	cp = xmalloc(len);
82 	strlcpy(cp, str, len);
83 	return cp;
84 }
85 
86 int
87 xasprintf(char **ret, const char *fmt, ...)
88 {
89 	va_list ap;
90 	int i;
91 
92 	va_start(ap, fmt);
93 	i = vasprintf(ret, fmt, ap);
94 	va_end(ap);
95 
96 	if (i < 0 || *ret == NULL)
97 		fatal("xasprintf: could not allocate memory");
98 
99 	return (i);
100 }
101