-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackAllocator.c
More file actions
61 lines (46 loc) · 1.15 KB
/
StackAllocator.c
File metadata and controls
61 lines (46 loc) · 1.15 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define POOL_SIZE 1024
size_t offset;
int nHeaders = 10;
void* basePtr;
typedef struct {
void* dataPtr;
size_t dataSz;
}Header;
void allignHeader(uintptr_t* headerPtr) {
int rem = *headerPtr % 8;
if (rem != 0) {
*headerPtr += 8 - rem;
printf("Padding: %d\n", 8 - rem);
}
}
void* stackAlloc(size_t size) {
if (size + offset > POOL_SIZE || !nHeaders) return NULL;
uintptr_t headerPtr = (uintptr_t)basePtr + offset;
allignHeader(&headerPtr);
printf("Aligned header: 0x%lu\n", headerPtr);
Header* header = (Header*)headerPtr;
header->dataPtr = header + 1;
header->dataSz = size;
offset += sizeof(Header) + size;
nHeaders--;
return header->dataPtr;
}
unsigned int initStack() {
void* stack = malloc(sizeof(Header) * 10 + POOL_SIZE);
if (!stack) return 0;
basePtr = stack;
return 1;
}
int main() {
initStack();
printf("Stack ptr; 0x%lu\n", basePtr);
void* allocated = stackAlloc(7);
printf("Allocation ptr; 0x%lu\n", allocated);
printf("==================\n\n");
void* allocated2 = stackAlloc(7);
printf("Allocation ptr; 0x%lu\n", allocated2);
printf("==================\n\n");
}