-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.cpp
89 lines (69 loc) · 2.14 KB
/
example.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/// @file Example usage.
#include "MemoryAllocators.h"
#include <cstdio>
struct ExampleStruct
{
unsigned int mCount;
float mFloat;
};
// example error callback
static void errorCallback(const char* inErrorMessage)
{
fprintf(stderr, inErrorMessage);
// c++ exception handling can be added here
}
int main(void)
{
Mem::errorCallback = &errorCallback;
{ // Bump Allocator Example
printf("Bump Allocator Example:\n");
Mem::BumpAllocator bumpAllocator{};
bumpAllocator.Create(Mem::SizeKB(1));
int* mem1 = (int*)bumpAllocator.Alloc(sizeof(int));
*mem1 = 7;
float* mem2 = (float*)bumpAllocator.Alloc(sizeof(float));
*mem2 = 3.14;
ExampleStruct* mem3 = (ExampleStruct*)bumpAllocator.Alloc(sizeof(ExampleStruct));
*mem3 = ExampleStruct{7, 1.0f};
printf("mem1 = %i\n", *mem1);
printf("mem2 = %f\n", *mem2);
printf("mem3->mCount = %u\n", mem3->mCount);
printf("mem3->mFloat = %f\n", mem3->mFloat);
printf("%zu bytes left.\n", bumpAllocator.GetRemainingBytes());
bumpAllocator.Reset();
bumpAllocator.Destroy();
putchar('\n');
}
{ // Pool Allocator Example
printf("Pool Allocator Example:\n");
Mem::PoolAllocator poolAllocator{};
poolAllocator.Create(sizeof(double), 8);
poolAllocator.PrintUsage();
Mem::PoolAllocator::Allocation mem1 = poolAllocator.Alloc();
*(double*)mem1.mMemory = 7.0;
printf("mem1 = %f\n", *(double*)mem1.mMemory);
poolAllocator.PrintUsage();
poolAllocator.Free(mem1);
printf("mem1 freed!\n");
poolAllocator.PrintUsage();
Mem::PoolAllocator::Allocation mem2 = poolAllocator.Alloc();
*(double*)mem2.mMemory = 8.0;
printf("mem2 = %f\n", *(double*)mem2.mMemory);
Mem::PoolAllocator::Allocation mem3 = poolAllocator.Alloc();
*(double*)mem3.mMemory = 9.0;
printf("mem3 = %f\n", *(double*)mem3.mMemory);
poolAllocator.PrintUsage();
poolAllocator.Reset();
printf("all memory freed!\n");
poolAllocator.PrintUsage();
for (size_t i = 0; i < poolAllocator.GetNumMaxElements(); i++)
{
Mem::PoolAllocator::Allocation mem0 = poolAllocator.Alloc();
}
printf("memory filled!\n");
poolAllocator.PrintUsage();
poolAllocator.Reset();
poolAllocator.Destroy();
putchar('\n');
}
}