|
2 | 2 | #include <assert.h> |
3 | 3 | #include <stdlib.h> |
4 | 4 |
|
5 | | -int main() { |
6 | | - int *p = (int *)malloc(sizeof(int)); |
7 | | - *p = 42; |
8 | | - assert(*p == 42); |
9 | | - free(p); |
| 5 | +#define ALLOC_TESTS(MALLOC, FREE, REALLOC, CALLOC) \ |
| 6 | + do { \ |
| 7 | + int *p = (int *)MALLOC(sizeof(int)); \ |
| 8 | + *p = 42; \ |
| 9 | + assert(*p == 42); \ |
| 10 | + FREE(p); \ |
| 11 | + \ |
| 12 | + int *arr = (int *)MALLOC(4 * sizeof(int)); \ |
| 13 | + for (int i = 0; i < 4; i++) { \ |
| 14 | + arr[i] = i * 10; \ |
| 15 | + } \ |
| 16 | + assert(arr[0] == 0); \ |
| 17 | + assert(arr[3] == 30); \ |
| 18 | + FREE(arr); \ |
| 19 | + \ |
| 20 | + int *grow = (int *)MALLOC(2 * sizeof(int)); \ |
| 21 | + grow[0] = 1; \ |
| 22 | + grow[1] = 2; \ |
| 23 | + grow = (int *)REALLOC(grow, 4 * sizeof(int)); \ |
| 24 | + grow[2] = 3; \ |
| 25 | + grow[3] = 4; \ |
| 26 | + assert(grow[0] == 1); \ |
| 27 | + assert(grow[1] == 2); \ |
| 28 | + assert(grow[2] == 3); \ |
| 29 | + assert(grow[3] == 4); \ |
| 30 | + FREE(grow); \ |
| 31 | + \ |
| 32 | + int *zeros = (int *)CALLOC(4, sizeof(int)); \ |
| 33 | + for (int i = 0; i < 4; i++) { \ |
| 34 | + assert(zeros[i] == 0); \ |
| 35 | + } \ |
| 36 | + FREE(zeros); \ |
| 37 | + } while (0) |
10 | 38 |
|
11 | | - int *arr = (int *)malloc(4 * sizeof(int)); |
12 | | - for (int i = 0; i < 4; i++) { |
13 | | - arr[i] = i * 10; |
14 | | - } |
15 | | - assert(arr[0] == 0); |
16 | | - assert(arr[3] == 30); |
17 | | - free(arr); |
| 39 | +int main() { |
| 40 | + ALLOC_TESTS(malloc, free, realloc, calloc); |
18 | 41 |
|
19 | | - int *grow = (int *)malloc(2 * sizeof(int)); |
20 | | - grow[0] = 1; |
21 | | - grow[1] = 2; |
22 | | - grow = (int *)realloc(grow, 4 * sizeof(int)); |
23 | | - grow[2] = 3; |
24 | | - grow[3] = 4; |
25 | | - assert(grow[0] == 1); |
26 | | - assert(grow[1] == 2); |
27 | | - assert(grow[2] == 3); |
28 | | - assert(grow[3] == 4); |
29 | | - free(grow); |
| 42 | + void *(*pmalloc)(size_t) = malloc; |
| 43 | + void (*pfree)(void *) = free; |
| 44 | + void *(*prealloc)(void *, size_t) = realloc; |
| 45 | + void *(*pcalloc)(size_t, size_t) = calloc; |
30 | 46 |
|
31 | | - int *zeros = (int *)calloc(4, sizeof(int)); |
32 | | - for (int i = 0; i < 4; i++) { |
33 | | - assert(zeros[i] == 0); |
34 | | - } |
35 | | - free(zeros); |
| 47 | + ALLOC_TESTS(pmalloc, pfree, prealloc, pcalloc); |
36 | 48 |
|
37 | 49 | return 0; |
38 | 50 | } |
0 commit comments