xref: /titanic_50/usr/src/cmd/ssh/libssh/common/xmalloc.c (revision 47b374ff8413339e27ddb691c18d22ffe3482515)
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * Versions of malloc and friends that check their results, and never return
6  * failure (they call fatal if they encounter an error).
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  */
14 
15 #include "includes.h"
16 RCSID("$OpenBSD: xmalloc.c,v 1.16 2001/07/23 18:21:46 stevesk Exp $");
17 
18 #pragma ident	"%Z%%M%	%I%	%E% SMI"
19 
20 #include "xmalloc.h"
21 #include "log.h"
22 
23 void *
xmalloc(size_t size)24 xmalloc(size_t size)
25 {
26 	void *ptr;
27 
28 	if (size == 0)
29 		fatal("xmalloc: zero size");
30 	ptr = malloc(size);
31 	if (ptr == NULL)
32 		fatal("xmalloc: out of memory (allocating %lu bytes)", (u_long) size);
33 	return ptr;
34 }
35 
36 void *
xcalloc(size_t nmemb,size_t size)37 xcalloc(size_t nmemb, size_t size)
38 {
39 	void *ptr;
40 
41 	if (size == 0 || nmemb == 0)
42 		fatal("xcalloc: zero size");
43 	if (SIZE_T_MAX / nmemb < size)
44 		fatal("xcalloc: nmemb * size > SIZE_T_MAX");
45 	ptr = calloc(nmemb, size);
46 	if (ptr == NULL)
47 		fatal("xcalloc: out of memory (allocating %lu bytes)",
48 		    (u_long)(size * nmemb));
49 	return ptr;
50 }
51 
52 void *
xrealloc(void * ptr,size_t new_size)53 xrealloc(void *ptr, size_t new_size)
54 {
55 	void *new_ptr;
56 
57 	if (new_size == 0)
58 		fatal("xrealloc: zero size");
59 	if (ptr == NULL)
60 		new_ptr = malloc(new_size);
61 	else
62 		new_ptr = realloc(ptr, new_size);
63 	if (new_ptr == NULL)
64 		fatal("xrealloc: out of memory (new_size %lu bytes)", (u_long) new_size);
65 	return new_ptr;
66 }
67 
68 void
xfree(void * ptr)69 xfree(void *ptr)
70 {
71 	if (ptr == NULL)
72 		fatal("xfree: NULL pointer given as argument");
73 	free(ptr);
74 }
75 
76 char *
xstrdup(const char * str)77 xstrdup(const char *str)
78 {
79 	size_t len;
80 	char *cp;
81 
82 	len = strlen(str) + 1;
83 	cp = xmalloc(len);
84 	strlcpy(cp, str, len);
85 	return cp;
86 }
87