| 1 |
/* |
| 2 |
* This header was copied from util-linux at fall 2011. |
| 3 |
*/ |
| 4 |
|
| 5 |
/* |
| 6 |
* General memory allocation wrappers for malloc, realloc, calloc |
| 7 |
* and strdup. |
| 8 |
*/ |
| 9 |
|
| 10 |
#ifndef PROCPS_NG_XALLOC_H |
| 11 |
#define PROCPS_NG_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 |
|
| 22 |
static inline __ul_alloc_size(1) |
| 23 |
void *xmalloc(const size_t size) |
| 24 |
{ |
| 25 |
void *ret = malloc(size); |
| 26 |
if (!ret && size) |
| 27 |
xerrx(XALLOC_EXIT_CODE, "cannot allocate %zu bytes", size); |
| 28 |
return ret; |
| 29 |
} |
| 30 |
|
| 31 |
static inline __ul_alloc_size(2) |
| 32 |
void *xrealloc(void *ptr, const size_t size) |
| 33 |
{ |
| 34 |
void *ret = realloc(ptr, size); |
| 35 |
if (!ret && size) |
| 36 |
xerrx(XALLOC_EXIT_CODE, "cannot allocate %zu bytes", size); |
| 37 |
return ret; |
| 38 |
} |
| 39 |
|
| 40 |
static inline __ul_calloc_size(1, 2) |
| 41 |
void *xcalloc(const size_t nelems, const size_t size) |
| 42 |
{ |
| 43 |
void *ret = calloc(nelems, size); |
| 44 |
if (!ret && size && nelems) |
| 45 |
xerrx(XALLOC_EXIT_CODE, "cannot allocate %zu bytes", nelems*size); |
| 46 |
return ret; |
| 47 |
} |
| 48 |
|
| 49 |
static inline char *xstrdup(const char *str) |
| 50 |
{ |
| 51 |
char *ret; |
| 52 |
if (!str) |
| 53 |
return NULL; |
| 54 |
ret = strdup(str); |
| 55 |
if (!ret) |
| 56 |
xerrx(XALLOC_EXIT_CODE, "cannot duplicate string"); |
| 57 |
return ret; |
| 58 |
} |
| 59 |
|
| 60 |
#endif /* PROCPS_NG_XALLOC_H */ |