Derive-C
Loading...
Searching...
No Matches
template.h
Go to the documentation of this file.
1
3// different instances of data structures, only see the allocations we want
4// to.
5
6#include <stdio.h>
7
8#include <derive-c/core.h>
9#include <derive-c/panic.h>
10#include <derive-c/self.h>
11
12#ifndef ALLOC
13#ifndef __clang_analyzer__
14#error "The allocator being debugged must be defined"
15#endif
17#define ALLOC nullalloc
18#endif
19
20typedef struct {
21 char const* name;
23} SELF;
24
25static SELF NAME(SELF, new)(char const* name, ALLOC* alloc) {
26 return (SELF){.name = name, .base = alloc};
27}
28
29static void* NAME(SELF, malloc)(SELF* self, size_t size) {
30 DEBUG_ASSERT(self);
31 void* ptr = NAME(ALLOC, malloc)(self->base, size);
32 if (ptr) {
33 printf("%s allocated %zu bytes at %p\n", self->name, size, ptr);
34 } else {
35 printf("%s failed to allocate %zu bytes\n", self->name, size);
36 }
37 return ptr;
38}
39
40static void* NAME(SELF, calloc)(SELF* self, size_t count, size_t size) {
41 DEBUG_ASSERT(self);
42 void* ptr = NAME(ALLOC, calloc)(self->base, count, size);
43 if (ptr) {
44 printf("%s allocated %zu bytes at %p\n", self->name, count * size, ptr);
45 } else {
46 printf("%s failed to allocate %zu bytes\n", self->name, count * size);
47 }
48 return ptr;
49}
50
51static void* NAME(SELF, realloc)(SELF* self, void* ptr, size_t size) {
52 DEBUG_ASSERT(self);
53 void* new_ptr = NAME(ALLOC, realloc)(self->base, ptr, size);
54 if (new_ptr) {
55 printf("%s reallocated memory at %p to %zu bytes\n", self->name, new_ptr, size);
56 } else {
57 printf("%s failed to reallocate memory at %p to %zu bytes\n", self->name, ptr, size);
58 }
59 return new_ptr;
60}
61
62static void NAME(SELF, free)(SELF* self, void* ptr) {
63 DEBUG_ASSERT(self);
64 printf("%s freeing memory at %p\n", self->name, ptr);
65 NAME(ALLOC, free)(self->base, ptr);
66}
67
68#undef ALLOC
69#undef SELF
#define ALLOC
An allocator that prints to stdout when it allocates or frees memory.
Definition template.h:17
static void free(SELF *self, void *ptr)
Definition template.h:62
static void * realloc(SELF *self, void *ptr, size_t size)
Definition template.h:51
static void * malloc(SELF *self, size_t size)
Definition template.h:29
static void * calloc(SELF *self, size_t count, size_t size)
Definition template.h:40
#define SELF
Definition template.h:70
#define NAME(pre, post)
Definition core.h:5
#define DEBUG_ASSERT(expr)
Definition panic.h:23
ALLOC * base
Definition template.h:22
char const * name
Definition template.h:21
static INDEX_TYPE size(SELF const *self)
Definition template.h:207
#define ALLOC
A simple vector.
Definition template.h:15