1 #include "test_allocator.h"
7 // How many alloc calls we expect
8 int alloc_calls_expected;
9 // How many alloc calls we got
11 // Array of booleans indicating whether to return a block or fail with NULL
12 call_expectation *expectations;
14 void set_mock_malloc(int calls, ...) {
16 va_start(args, calls);
17 alloc_calls_expected = calls;
19 expectations = calloc(calls, sizeof(expectations));
20 for (int i = 0; i < calls; i++) {
21 // Promotable types, baby
22 expectations[i] = va_arg(args, call_expectation);
27 void finalize_mock_malloc(void) {
28 assert_int_equal(alloc_calls, alloc_calls_expected);
32 void print_backtrace() {
35 int frames = backtrace(buffer, 128);
36 char **symbols = backtrace_symbols(buffer, frames);
37 // Skip this function and the caller
38 for (int i = 2; i < frames; ++i) {
39 printf("%s\n", symbols[i]);
45 void *instrumented_malloc(size_t size) {
46 if (alloc_calls >= alloc_calls_expected) {
50 if (expectations[alloc_calls] == MALLOC) {
53 } else if (expectations[alloc_calls] == MALLOC_FAIL) {
60 "Unexpected call to malloc(%zu) at position %d of %d; expected %d\n",
61 size, alloc_calls, alloc_calls_expected,
62 alloc_calls < alloc_calls_expected ? expectations[alloc_calls] : -1);
68 void *instrumented_realloc(void *ptr, size_t size) {
69 if (alloc_calls >= alloc_calls_expected) {
73 if (expectations[alloc_calls] == REALLOC) {
75 return realloc(ptr, size);
76 } else if (expectations[alloc_calls] == REALLOC_FAIL) {
83 "Unexpected call to realloc(%zu) at position %d of %d; expected %d\n",
84 size, alloc_calls, alloc_calls_expected,
85 alloc_calls < alloc_calls_expected ? expectations[alloc_calls] : -1);