]>
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 void __attribute__((__noreturn__
))
23 __err_oom(const char *file
, unsigned int line
)
25 err(XALLOC_EXIT_CODE
, "%s: %u: cannot allocate memory", file
, line
);
28 #define err_oom() __err_oom(__FILE__, __LINE__)
30 static inline __ul_alloc_size(1) __ul_returns_nonnull
31 void *xmalloc(const size_t size
)
33 void *ret
= malloc(size
);
36 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
40 static inline __ul_alloc_size(2) __ul_returns_nonnull
41 void *xrealloc(void *ptr
, const size_t size
)
43 void *ret
= realloc(ptr
, size
);
46 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
50 static inline __ul_calloc_size(1, 2) __ul_returns_nonnull
51 void *xcalloc(const size_t nelems
, const size_t size
)
53 void *ret
= calloc(nelems
, size
);
55 if (!ret
&& size
&& nelems
)
56 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
60 static inline char __attribute__((warn_unused_result
)) __ul_returns_nonnull
61 *xstrdup(const char *str
)
71 err(XALLOC_EXIT_CODE
, "cannot duplicate string");
75 static inline char * __attribute__((warn_unused_result
)) __ul_returns_nonnull
76 xstrndup(const char *str
, size_t size
)
83 ret
= strndup(str
, size
);
86 err(XALLOC_EXIT_CODE
, "cannot duplicate string");
91 static inline int __attribute__ ((__format__(printf
, 2, 3)))
92 xasprintf(char **strp
, const char *fmt
, ...)
97 ret
= vasprintf(&(*strp
), fmt
, args
);
100 err(XALLOC_EXIT_CODE
, "cannot allocate string");
104 static inline int __attribute__ ((__format__(printf
, 2, 0)))
105 xvasprintf(char **strp
, const char *fmt
, va_list ap
)
107 int ret
= vasprintf(&(*strp
), fmt
, ap
);
109 err(XALLOC_EXIT_CODE
, "cannot allocate string");
114 static inline char * __attribute__((warn_unused_result
)) xgethostname(void)
117 size_t sz
= get_hostname_max() + 1;
119 name
= xmalloc(sizeof(char) * sz
);
121 if (gethostname(name
, sz
) != 0) {