]>
git.ipfire.org Git - thirdparty/util-linux.git/blob - include/xalloc.h
2 * Copyright (C) 2010 Davidlohr Bueso <dave@gnu.org>
4 * This file may be redistributed under the terms of the
5 * GNU Lesser General Public License.
7 * General memory allocation wrappers for malloc, realloc, calloc and strdup
10 #ifndef UTIL_LINUX_XALLOC_H
11 #define UTIL_LINUX_XALLOC_H
18 #ifndef XALLOC_EXIT_CODE
19 # define XALLOC_EXIT_CODE EXIT_FAILURE
22 static inline __ul_alloc_size(1)
23 void *xmalloc(const size_t size
)
25 void *ret
= malloc(size
);
28 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
32 static inline __ul_alloc_size(2)
33 void *xrealloc(void *ptr
, const size_t size
)
35 void *ret
= realloc(ptr
, size
);
38 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
42 static inline __ul_calloc_size(1, 2)
43 void *xcalloc(const size_t nelems
, const size_t size
)
45 void *ret
= calloc(nelems
, size
);
47 if (!ret
&& size
&& nelems
)
48 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
52 static inline char *xstrdup(const char *str
)
62 err(XALLOC_EXIT_CODE
, "cannot duplicate string");
66 static inline char *xstrndup(const char *str
, size_t size
)
73 ret
= strndup(str
, size
);
76 err(XALLOC_EXIT_CODE
, "cannot duplicate string");
81 static inline int __attribute__ ((__format__(printf
, 2, 3)))
82 xasprintf(char **strp
, const char *fmt
, ...)
87 ret
= vasprintf(&(*strp
), fmt
, args
);
90 err(XALLOC_EXIT_CODE
, "cannot allocate string");
95 static inline char *xgethostname(void)
98 size_t sz
= get_hostname_max() + 1;
100 name
= xmalloc(sizeof(char) * sz
);
102 if (gethostname(name
, sz
) != 0) {