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