1 |
#include "../io/log.h" |
2 |
#include <stdlib.h> |
3 |
#include "utils.h" |
4 |
#include "xmalloc.h" |
5 |
|
6 |
#define OLDPTR_NONE ((unsigned long long int *)0xFFFFFFFFFFFFFFFFUL) |
7 |
|
8 |
static _Noreturn void xalloc_failed(const char *fn_name, size_t bufsize, size_t nblks, void *oldptr) |
9 |
{ |
10 |
if (((unsigned long long int *)oldptr) != OLDPTR_NONE) |
11 |
log_fatal("%s(ptr: %p, size: %zu): failed to allocate memory: %s", fn_name, oldptr, bufsize, get_last_error()); |
12 |
else |
13 |
log_fatal("%s(size: %zu, nblks: %zu): failed to allocate memory: %s", fn_name, bufsize, nblks, get_last_error()); |
14 |
|
15 |
exit(EXIT_FAILURE); |
16 |
} |
17 |
|
18 |
void *xmalloc(size_t size) |
19 |
{ |
20 |
void *ptr = malloc(size); |
21 |
|
22 |
if (ptr == NULL) |
23 |
{ |
24 |
xalloc_failed(__func__, size, 1, OLDPTR_NONE); |
25 |
return NULL; |
26 |
} |
27 |
|
28 |
return ptr; |
29 |
} |
30 |
|
31 |
void *xcalloc(size_t n, size_t size) |
32 |
{ |
33 |
void *ptr = calloc(n, size); |
34 |
|
35 |
if (ptr == NULL) |
36 |
{ |
37 |
xalloc_failed(__func__, size, n, OLDPTR_NONE); |
38 |
return NULL; |
39 |
} |
40 |
|
41 |
return ptr; |
42 |
} |
43 |
|
44 |
void *xrealloc(void *oldptr, size_t newsize) |
45 |
{ |
46 |
void *ptr = realloc(oldptr, newsize); |
47 |
|
48 |
if (ptr == NULL) |
49 |
{ |
50 |
xalloc_failed(__func__, newsize, 1, oldptr); |
51 |
return NULL; |
52 |
} |
53 |
|
54 |
return ptr; |
55 |
} |