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