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