]>
git.ipfire.org Git - thirdparty/util-linux.git/blob - include/xalloc.h
2 * SPDX-License-Identifier: LGPL-2.1-or-later
4 * Copyright (C) 2010 Davidlohr Bueso <dave@gnu.org>
5 * Copyright (C) 2010-2022 Karel Zak <kzak@redhat.com>
7 * This file may be redistributed under the terms of the
8 * GNU Lesser General Public License.
10 * General memory allocation wrappers for malloc, realloc, calloc and strdup
13 #ifndef UTIL_LINUX_XALLOC_H
14 #define UTIL_LINUX_XALLOC_H
21 #ifndef XALLOC_EXIT_CODE
22 # define XALLOC_EXIT_CODE EXIT_FAILURE
28 void *xmalloc(const size_t size
)
30 void *ret
= malloc(size
);
33 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
40 void *xrealloc(void *ptr
, const size_t size
)
42 void *ret
= realloc(ptr
, size
);
45 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
50 __ul_calloc_size(2, 3)
52 void *xreallocarray(void *ptr
, const size_t nelems
, const size_t size
)
54 void *ret
= reallocarray(ptr
, nelems
, size
);
56 if (!ret
&& size
&& nelems
)
57 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
62 __ul_calloc_size(1, 2)
64 void *xcalloc(const size_t nelems
, const size_t size
)
66 void *ret
= calloc(nelems
, size
);
68 if (!ret
&& size
&& nelems
)
69 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
74 __attribute__((warn_unused_result
))
76 char *xstrdup(const char *str
)
83 err(XALLOC_EXIT_CODE
, "cannot duplicate string");
88 __attribute__((warn_unused_result
))
90 char *xstrndup(const char *str
, size_t size
)
95 ret
= strndup(str
, size
);
97 err(XALLOC_EXIT_CODE
, "cannot duplicate string");
103 __attribute__((__format__(printf
, 2, 3)))
104 int xasprintf(char **strp
, const char *fmt
, ...)
110 ret
= vasprintf(&(*strp
), fmt
, args
);
113 err(XALLOC_EXIT_CODE
, "cannot allocate string");
118 __attribute__((__format__(printf
, 2, 0)))
119 int xvasprintf(char **strp
, const char *fmt
, va_list ap
)
121 int ret
= vasprintf(&(*strp
), fmt
, ap
);
124 err(XALLOC_EXIT_CODE
, "cannot allocate string");
130 __attribute__((warn_unused_result
))
131 char *xgethostname(void)
134 size_t sz
= get_hostname_max() + 1;
136 name
= xmalloc(sizeof(char) * sz
);
137 if (gethostname(name
, sz
) != 0) {