]> git.ipfire.org Git - thirdparty/util-linux.git/blob - include/xalloc.h
include/ttyutils: define values if missing.
[thirdparty/util-linux.git] / include / xalloc.h
1 /*
2 * Copyright (C) 2010 Davidlohr Bueso <dave@gnu.org>
3 *
4 * This file may be redistributed under the terms of the
5 * GNU Lesser General Public License.
6 *
7 * General memory allocation wrappers for malloc, realloc, calloc and strdup
8 */
9
10 #ifndef UTIL_LINUX_XALLOC_H
11 #define UTIL_LINUX_XALLOC_H
12
13 #include <stdlib.h>
14 #include <string.h>
15
16 #include "c.h"
17
18 #ifndef XALLOC_EXIT_CODE
19 # define XALLOC_EXIT_CODE EXIT_FAILURE
20 #endif
21
22 static inline void __err_oom(const char *file, unsigned int line)
23 {
24 err(XALLOC_EXIT_CODE, "%s: %u: cannot allocate memory", file, line);
25 }
26
27 #define err_oom() __err_oom(__FILE__, __LINE__)
28
29 static inline __ul_alloc_size(1)
30 void *xmalloc(const size_t size)
31 {
32 void *ret = malloc(size);
33
34 if (!ret && size)
35 err(XALLOC_EXIT_CODE, "cannot allocate %zu bytes", size);
36 return ret;
37 }
38
39 static inline __ul_alloc_size(2)
40 void *xrealloc(void *ptr, const size_t size)
41 {
42 void *ret = realloc(ptr, size);
43
44 if (!ret && size)
45 err(XALLOC_EXIT_CODE, "cannot allocate %zu bytes", size);
46 return ret;
47 }
48
49 static inline __ul_calloc_size(1, 2)
50 void *xcalloc(const size_t nelems, const size_t size)
51 {
52 void *ret = calloc(nelems, size);
53
54 if (!ret && size && nelems)
55 err(XALLOC_EXIT_CODE, "cannot allocate %zu bytes", size);
56 return ret;
57 }
58
59 static inline char __attribute__((warn_unused_result)) *xstrdup(const char *str)
60 {
61 char *ret;
62
63 if (!str)
64 return NULL;
65
66 ret = strdup(str);
67
68 if (!ret)
69 err(XALLOC_EXIT_CODE, "cannot duplicate string");
70 return ret;
71 }
72
73 static inline char * __attribute__((warn_unused_result)) xstrndup(const char *str, size_t size)
74 {
75 char *ret;
76
77 if (!str)
78 return NULL;
79
80 ret = strndup(str, size);
81
82 if (!ret)
83 err(XALLOC_EXIT_CODE, "cannot duplicate string");
84 return ret;
85 }
86
87
88 static inline int __attribute__ ((__format__(printf, 2, 3)))
89 xasprintf(char **strp, const char *fmt, ...)
90 {
91 int ret;
92 va_list args;
93 va_start(args, fmt);
94 ret = vasprintf(&(*strp), fmt, args);
95 va_end(args);
96 if (ret < 0)
97 err(XALLOC_EXIT_CODE, "cannot allocate string");
98 return ret;
99 }
100
101 static inline int __attribute__ ((__format__(printf, 2, 0)))
102 xvasprintf(char **strp, const char *fmt, va_list ap)
103 {
104 int ret = vasprintf(&(*strp), fmt, ap);
105 if (ret < 0)
106 err(XALLOC_EXIT_CODE, "cannot allocate string");
107 return ret;
108 }
109
110
111 static inline char * __attribute__((warn_unused_result)) xgethostname(void)
112 {
113 char *name;
114 size_t sz = get_hostname_max() + 1;
115
116 name = xmalloc(sizeof(char) * sz);
117
118 if (gethostname(name, sz) != 0) {
119 free(name);
120 return NULL;
121 }
122 name[sz - 1] = '\0';
123 return name;
124 }
125
126 #endif