]> git.meshlink.io Git - meshlink/blob - src/xalloc.h
Avoid allocating packet buffers unnecessarily.
[meshlink] / src / xalloc.h
1 #ifndef MESHLINK_XALLOC_H
2 #define MESHLINK_XALLOC_H
3
4 /*
5    xalloc.h -- malloc and related functions with out of memory checking
6    Copyright (C) 2014, 2017 Guus Sliepen <guus@meshlink.io>
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2, or (at your option)
11    any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License along
19    with this program; if not, write to the Free Software Foundation, Inc., Foundation,
20    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 static inline void *xmalloc(size_t n) __attribute__((__malloc__));
24 static inline void *xmalloc(size_t n) {
25         void *p = malloc(n);
26
27         if(!p) {
28                 abort();
29         }
30
31         return p;
32 }
33
34 static inline void *xzalloc(size_t n) __attribute__((__malloc__));
35 static inline void *xzalloc(size_t n) {
36         void *p = calloc(1, n);
37
38         if(!p) {
39                 abort();
40         }
41
42         return p;
43 }
44
45 static inline void *xrealloc(void *p, size_t n) {
46         p = realloc(p, n);
47
48         if(!p) {
49                 abort();
50         }
51
52         return p;
53 }
54
55 static inline char *xstrdup(const char *s) __attribute__((__malloc__));
56 static inline char *xstrdup(const char *s) {
57         char *p = strdup(s);
58
59         if(!p) {
60                 abort();
61         }
62
63         return p;
64 }
65
66 static inline int xvasprintf(char **strp, const char *fmt, va_list ap) {
67 #ifdef HAVE_MINGW
68         char buf[1024];
69         int result = vsnprintf(buf, sizeof(buf), fmt, ap);
70
71         if(result < 0) {
72                 abort();
73         }
74
75         *strp = xstrdup(buf);
76 #else
77         int result = vasprintf(strp, fmt, ap);
78
79         if(result < 0) {
80                 abort();
81         }
82
83 #endif
84         return result;
85 }
86
87 static inline int xasprintf(char **strp, const char *fmt, ...) __attribute__((__format__(printf, 2, 3)));
88 static inline int xasprintf(char **strp, const char *fmt, ...) {
89         va_list ap;
90         va_start(ap, fmt);
91         int result = xvasprintf(strp, fmt, ap);
92         va_end(ap);
93         return result;
94 }
95
96 #endif