blob: 7b685e71843172d221ef94a0484de1b7cd1fee58 [file] [log] [blame]
bigbiff bigbiffe60683a2013-02-22 20:55:50 -05001/*
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
22static inline __ul_alloc_size(1)
23void *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
32static inline __ul_alloc_size(2)
33void *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
42static inline __ul_calloc_size(1, 2)
43void *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
52static 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
66static inline int __attribute__ ((__format__(printf, 2, 3)))
67 xasprintf(char **strp, const char *fmt, ...)
68{
69 int ret;
70 va_list args;
71 va_start(args, fmt);
72 ret = vasprintf(&(*strp), fmt, args);
73 va_end(args);
74 if (ret < 0)
75 err(XALLOC_EXIT_CODE, "cannot allocate string");
76 return ret;
77}
78
79
80static inline char *xgethostname(void)
81{
82 char *name;
83 size_t sz = get_hostname_max() + 1;
84
85 name = xmalloc(sizeof(char) * sz);
86 if (gethostname(name, sz) != 0)
87 return NULL;
88
89 name[sz - 1] = '\0';
90 return name;
91}
92
93#endif