]>
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 __err_oom(const char *file
, unsigned int line
)
24 err(XALLOC_EXIT_CODE
, "%s: %u: cannot allocate memory", file
, line
);
27 #define err_oom() __err_oom(__FILE__, __LINE__)
29 static inline __ul_alloc_size(1)
30 void *xmalloc(const size_t size
)
32 void *ret
= malloc(size
);
35 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
39 static inline __ul_alloc_size(2)
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
);
49 static inline __ul_calloc_size(1, 2)
50 void *xcalloc(const size_t nelems
, const size_t size
)
52 void *ret
= calloc(nelems
, size
);
54 if (!ret
&& size
&& nelems
)
55 err(XALLOC_EXIT_CODE
, "cannot allocate %zu bytes", size
);
59 static inline char __attribute__((warn_unused_result
)) *xstrdup(const char *str
)
69 err(XALLOC_EXIT_CODE
, "cannot duplicate string");
73 static inline char * __attribute__((warn_unused_result
)) xstrndup(const char *str
, size_t size
)
80 ret
= strndup(str
, size
);
83 err(XALLOC_EXIT_CODE
, "cannot duplicate string");
88 static inline int __attribute__ ((__format__(printf
, 2, 3)))
89 xasprintf(char **strp
, const char *fmt
, ...)
94 ret
= vasprintf(&(*strp
), fmt
, args
);
97 err(XALLOC_EXIT_CODE
, "cannot allocate string");
101 static inline int __attribute__ ((__format__(printf
, 2, 0)))
102 xvasprintf(char **strp
, const char *fmt
, va_list ap
)
104 int ret
= vasprintf(&(*strp
), fmt
, ap
);
106 err(XALLOC_EXIT_CODE
, "cannot allocate string");
111 static inline char * __attribute__((warn_unused_result
)) xgethostname(void)
114 size_t sz
= get_hostname_max() + 1;
116 name
= xmalloc(sizeof(char) * sz
);
118 if (gethostname(name
, sz
) != 0) {