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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
#include "memstack.h"
#include "test.h"
#define NUM_INTS 10
#define CAPACITY (NUM_INTS * sizeof(int))
// Create and destroy a statically-backed stack.
TEST_CASE(memstack_create) {
int memory[CAPACITY];
memstack stack = {0};
memstack_make(&stack, CAPACITY, memory);
memstack_del(&stack);
}
// Create and destroy a dynamically-backed stack.
TEST_CASE(mem_create_dyn) {
memstack stack = {0};
memstack_make(&stack, CAPACITY, nullptr);
memstack_del(&stack);
}
// Allocate all N ints.
TEST_CASE(memstack_allocate_until_full) {
memstack stack = {0};
memstack_make(&stack, CAPACITY, nullptr);
for (int i = 0; i < NUM_INTS; ++i) {
const int* block = memstack_alloc(&stack, sizeof(int));
TEST_TRUE(block != nullptr);
}
TEST_TRUE(memstack_size(&stack) == CAPACITY);
}
// Allocate all N ints, then free them.
TEST_CASE(memstack_fill_then_free) {
memstack stack = {0};
memstack_make(&stack, CAPACITY, nullptr);
int* blocks[NUM_INTS] = {nullptr};
for (int i = 0; i < NUM_INTS; ++i) {
blocks[i] = memstack_alloc(&stack, sizeof(int));
TEST_TRUE(blocks[i] != nullptr);
}
memstack_clear(&stack);
TEST_EQUAL(memstack_size(&stack), 0);
}
// Attempt to allocate blocks past the maximum stack size.
// The stack should handle the failed allocations gracefully.
TEST_CASE(memstack_allocate_beyond_max_size) {
memstack stack = {0};
memstack_make(&stack, CAPACITY, nullptr);
memstack_enable_traps(&stack, false);
// Fully allocate the stack.
for (int i = 0; i < NUM_INTS; ++i) {
TEST_TRUE(memstack_alloc(&stack, sizeof(int)) != nullptr);
}
// Past the end.
for (int i = 0; i < NUM_INTS; ++i) {
TEST_EQUAL(memstack_alloc(&stack, sizeof(int)), nullptr);
}
TEST_TRUE(memstack_size(&stack) == CAPACITY);
}
// Free blocks should always remain zeroed out.
// This tests the invariant right after creating the stack.
TEST_CASE(memstack_zero_free_blocks_after_creation) {
memstack stack = {0};
memstack_make(&stack, CAPACITY, nullptr);
for (int i = 0; i < NUM_INTS; ++i) {
const int* block = memstack_alloc(&stack, sizeof(int));
TEST_TRUE(block != nullptr);
TEST_EQUAL(*block, 0);
}
}
// Free blocks should always remain zeroed out.
// This tests the invariant after clearing the stack and allocating a new block.
TEST_CASE(memstack_zero_free_block_after_free) {
memstack stack = {0};
memstack_make(&stack, CAPACITY, nullptr);
for (int i = 0; i < NUM_INTS; ++i) {
const int* block = memstack_alloc(&stack, sizeof(int));
TEST_TRUE(block != nullptr);
TEST_EQUAL(*block, 0);
}
memstack_clear(&stack);
for (int i = 0; i < NUM_INTS; ++i) {
const int* block = memstack_alloc(&stack, sizeof(int));
TEST_TRUE(block != nullptr);
TEST_EQUAL(*block, 0);
}
}
int main() { return 0; }
|