Line | Branch | Exec | Source |
---|---|---|---|
1 | #include <errno.h> | ||
2 | #include <limits.h> | ||
3 | #include <stdarg.h> | ||
4 | #include <stdio.h> | ||
5 | #include <stdlib.h> | ||
6 | #include "xmalloc.h" | ||
7 | #include "debug.h" | ||
8 | #include "xsnprintf.h" | ||
9 | |||
10 | 83829 | static void *check_alloc(void *alloc) | |
11 | { | ||
12 |
1/2✗ Branch 0 (2→3) not taken.
✓ Branch 1 (2→4) taken 83829 times.
|
83829 | if (unlikely(alloc == NULL)) { |
13 | − | fatal_error(__func__, ENOMEM); | |
14 | } | ||
15 | 83829 | return alloc; | |
16 | } | ||
17 | |||
18 | // Like malloc(3), but calling fatal_error() on OOM and forbidding | ||
19 | // zero-sized allocations (thus never returning NULL) | ||
20 | 49845 | void *xmalloc(size_t size) | |
21 | { | ||
22 | 49845 | BUG_ON(size == 0); | |
23 | 49845 | return check_alloc(malloc(size)); | |
24 | } | ||
25 | |||
26 | 3858 | void *xcalloc(size_t nmemb, size_t size) | |
27 | { | ||
28 | 3858 | if (__STDC_VERSION__ < 202311L) { | |
29 | // ISO C23 (ยง7.24.3.2) requires calloc() to check for integer | ||
30 | // overflow in `nmemb * size`, but older C standards don't | ||
31 | xmul(nmemb, size); | ||
32 | } | ||
33 | |||
34 | 3858 | BUG_ON(nmemb == 0 || size == 0); | |
35 | 3858 | return check_alloc(calloc(nmemb, size)); | |
36 | } | ||
37 | |||
38 | 13934 | void *xrealloc(void *ptr, size_t size) | |
39 | { | ||
40 | 13934 | BUG_ON(size == 0); | |
41 | 13934 | return check_alloc(realloc(ptr, size)); | |
42 | } | ||
43 | |||
44 | 16192 | char *xstrdup(const char *str) | |
45 | { | ||
46 | 16192 | return check_alloc(strdup(str)); | |
47 | } | ||
48 | |||
49 | VPRINTF(1) | ||
50 | 2 | static char *xvasprintf(const char *format, va_list ap) | |
51 | { | ||
52 | 2 | va_list ap2; | |
53 | 2 | va_copy(ap2, ap); | |
54 | 2 | int n = vsnprintf(NULL, 0, format, ap2); | |
55 | 2 | va_end(ap2); | |
56 | |||
57 |
1/2✗ Branch 0 (2→3) not taken.
✓ Branch 1 (2→6) taken 2 times.
|
2 | if (unlikely(n < 0 || n == INT_MAX || n >= SIZE_MAX)) { |
58 | − | fatal_error(__func__, n < 0 ? errno : EOVERFLOW); | |
59 | } | ||
60 | |||
61 | 2 | char *str = xmalloc(n + 1); | |
62 | 2 | size_t m = xvsnprintf(str, n + 1, format, ap); | |
63 | 2 | BUG_ON(m != n); | |
64 | 2 | return str; | |
65 | } | ||
66 | |||
67 | 2 | char *xasprintf(const char *format, ...) | |
68 | { | ||
69 | 2 | va_list ap; | |
70 | 2 | va_start(ap, format); | |
71 | 2 | char *str = xvasprintf(format, ap); | |
72 | 2 | va_end(ap); | |
73 | 2 | return str; | |
74 | } | ||
75 |