]> git.ipfire.org Git - thirdparty/util-linux.git/blob - include/xalloc.h
lib/xalloc: add xstrndup()
[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 __ul_alloc_size(1)
23 void *xmalloc(const size_t size)
24 {
25 void *ret = malloc(size);
26
27 if (!ret && size)
28 err(XALLOC_EXIT_CODE, "cannot allocate %zu bytes", size);
29 return ret;
30 }
31
32 static inline __ul_alloc_size(2)
33 void *xrealloc(void *ptr, const size_t size)
34 {
35 void *ret = realloc(ptr, size);
36
37 if (!ret && size)
38 err(XALLOC_EXIT_CODE, "cannot allocate %zu bytes", size);
39 return ret;
40 }
41
42 static inline __ul_calloc_size(1, 2)
43 void *xcalloc(const size_t nelems, const size_t size)
44 {
45 void *ret = calloc(nelems, size);
46
47 if (!ret && size && nelems)
48 err(XALLOC_EXIT_CODE, "cannot allocate %zu bytes", size);
49 return ret;
50 }
51
52 static inline char *xstrdup(const char *str)
53 {
54 char *ret;
55
56 if (!str)
57 return NULL;
58
59 ret = strdup(str);
60
61 if (!ret)
62 err(XALLOC_EXIT_CODE, "cannot duplicate string");
63 return ret;
64 }
65
66 static inline char *xstrndup(const char *str, size_t size)
67 {
68 char *ret;
69
70 if (!str)
71 return NULL;
72
73 ret = strndup(str, size);
74
75 if (!ret)
76 err(XALLOC_EXIT_CODE, "cannot duplicate string");
77 return ret;
78 }
79
80
81 static inline int __attribute__ ((__format__(printf, 2, 3)))
82 xasprintf(char **strp, const char *fmt, ...)
83 {
84 int ret;
85 va_list args;
86 va_start(args, fmt);
87 ret = vasprintf(&(*strp), fmt, args);
88 va_end(args);
89 if (ret < 0)
90 err(XALLOC_EXIT_CODE, "cannot allocate string");
91 return ret;
92 }
93
94
95 static inline char *xgethostname(void)
96 {
97 char *name;
98 size_t sz = get_hostname_max() + 1;
99
100 name = xmalloc(sizeof(char) * sz);
101
102 if (gethostname(name, sz) != 0) {
103 free(name);
104 return NULL;
105 }
106 name[sz - 1] = '\0';
107 return name;
108 }
109
110 #endif