forked from xkxx/msp430-os
-
Notifications
You must be signed in to change notification settings - Fork 0
/
malloc.c
63 lines (57 loc) · 1.55 KB
/
malloc.c
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
#include "std.h"
#include "malloc.h"
// static memory allocator, inspired by FreeRTOS heap_2.c
// supports allocating/freeing memory, but does not merge free memory fragments
/**
* Static memory allocator
*
* @param size size (in bytes) of memory needed
* must be > 0 and < `HEAP_SIZE`
*
* @return address of allocated memory,
* or `NULL` if out of memory
*
*/
void* malloc(usize_t size) {
HeapMeta* meta;
// aligning memory
// http://stackoverflow.com/questions/1766535/bit-hack-round-off-to-multiple-of-8
size = (size + (MEMORY_ALIGN - 1)) & ~(MEMORY_ALIGN - 1);
if (size + sizeof(HeapMeta) <= HEAP_SIZE - heap_index) {
meta = (HeapMeta*) (heap + heap_index);
meta->isUsed = 1;
meta->size = size;
heap_index += size;
return meta + sizeof(HeapMeta);
}
else {
for (meta = (HeapMeta*) heap;
meta < (HeapMeta*) (heap + HEAP_SIZE);
meta += meta->size + sizeof(HeapMeta)) {
if(!meta->isUsed) {
meta->isUsed = 1;
return meta + sizeof(HeapMeta);
}
}
}
return NULL;
}
/**
* Release allocated memory
*
* @param ptr valid pointer to an allocated memory chunk
*
* The behavior is undefined if `ptr` points to memory that
* is not on heap or has been freed before
* CAREFUL: may cause gigantic explosion
*
*/
void free(void* ptr) {
HeapMeta* meta = (HeapMeta*)ptr - sizeof(HeapMeta);
meta->isUsed = 0;
// merge into free heap if it's the last block
if ((char*) ptr + meta->size == heap + heap_index) {
heap_index -= meta->size + sizeof(HeapMeta);
}
// TODO: check if neighbor blocks are free
}