-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmalloc.c
72 lines (53 loc) · 1.78 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
64
65
66
67
68
69
70
71
72
#include "Heap.h"
//
// Allocate a chunk of memory on the heap
//
void* malloc(size_t size) {
//Figure out the size alignment (should be 8 bytes)
if (size <= 0) {return NULL;}
size = NEXT_HEAP_ALIGN(size);
//Get the starting free block of the heap
pHeap_Block_t block = lock_heap();
if (!block) {return NULL;}
if (!valid_block(block)) {return (unlock_heap(), NULL);}
//Traverse the linked-list until a free block with enough space is discovered
while((!IS_FREE_BLOCK(block)) || (block->size < size)) {
//Make sure that this block is valid (to prevent heap corruption)
if (!valid_block(block)) {
//HEAP IS CORRUPTED!!!!
return (unlock_heap(), NULL);
}
// Go to the next block (if it exists)
if (block->next) {block = block->next; continue;}
//Okay, we are at the end of the heap, and there is no space left.
// So try to allocate more space on to the end of the heap
//
// Note: If this block is not free, then create a new block in the space
size_t toAdd;
if (IS_FREE_BLOCK(block)) {
toAdd = size-block->size;
} else {
toAdd = size+BLOCK_LENGTH;
}
size_t added = increase_heap(toAdd);
if (!added) {return (unlock_heap(), NULL); /* Alloc Error */ }
//Do I need to create a new block, or resize the current block
if (IS_FREE_BLOCK(block)) {
//Resize the old block
block->size += added;
block->checksum = block_checksum(block);
} else {
//Create a new block
block = create_block(block,NULL,BLOCK_SIZE(block),added-BLOCK_LENGTH);
}
}
//Figure out if I need to split this current block?
if (block->size > (size+BLOCK_LENGTH)) {
split_block(block,size);
}
//Make the size negative to indicate that this block is in use
block->size *= -1;
block->checksum = block_checksum(block);
unlock_heap();
return (void*) (block+1);
}