1 /*
2 * ircd-hybrid: an advanced, lightweight Internet Relay Chat Daemon (ircd)
3 *
4 * Copyright (c) 1997-2021 ircd-hybrid development team
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
19 * USA
20 */
21
22 /*! \file memory.c
23 * \brief Memory utilities.
24 * \version $Id: memory.c 9858 2021-01-01 04:43:42Z michael $
25 */
26
27 #include "stdinc.h"
28 #include "irc_string.h"
29 #include "memory.h"
30 #include "restart.h"
31
32
33 /*
34 * xcalloc - allocate memory, call outofmemory on failure
35 */
36 void *
xcalloc(size_t size)37 xcalloc(size_t size)
38 {
39 void *ret = calloc(1, size);
40
41 if (ret == NULL)
42 outofmemory();
43
44 return ret;
45 }
46
47 /*
48 * xrealloc - reallocate memory, call outofmemory on failure
49 */
50 void *
xrealloc(void * x,size_t y)51 xrealloc(void *x, size_t y)
52 {
53 void *ret = realloc(x, y);
54
55 if (y && ret == NULL)
56 outofmemory();
57
58 return ret;
59 }
60
61 void
xfree(void * x)62 xfree(void *x)
63 {
64 free(x);
65 }
66
67 void *
xstrdup(const char * s)68 xstrdup(const char *s)
69 {
70 void *ret = malloc(strlen(s) + 1);
71
72 if (ret == NULL)
73 outofmemory();
74
75 strcpy(ret, s);
76
77 return ret;
78 }
79
80 void *
xstrndup(const char * s,size_t len)81 xstrndup(const char *s, size_t len)
82 {
83 void *ret = malloc(len + 1);
84
85 if (ret == NULL)
86 outofmemory();
87
88 strlcpy(ret, s, len + 1);
89
90 return ret;
91 }
92
93 /* outofmemory()
94 *
95 * input - NONE
96 * output - NONE
97 * side effects - simply try to report there is a problem.
98 * Abort if it was called more than once
99 */
100 void
outofmemory(void)101 outofmemory(void)
102 {
103 static bool was_here = false;
104
105 if (was_here == false)
106 was_here = true;
107 else
108 abort();
109
110 server_die("out of memory", true);
111 }
112