-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmalloc.c
More file actions
27 lines (21 loc) · 821 Bytes
/
malloc.c
File metadata and controls
27 lines (21 loc) · 821 Bytes
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
#include "malloc.h"
Block *heap_start = NULL;
void *mymalloc(size_t size) {
if (size <= 0) return NULL;
// approximate the size to be multiple of BLOCK_SIZE
size = (size + BLOCK_SIZE - 1) & ~(BLOCK_SIZE - 1);
void *search_freed_heap; Block *last_node = NULL;
if ((search_freed_heap = search_heap(&last_node, size)) != NULL) return search_freed_heap;
// Request more Space from the OS
size_t total_size = size + BLOCK_SIZE;
void *ptr = mmap(NULL, total_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (ptr == MAP_FAILED) {
return NULL;
}
Block *new_block = (Block *) ptr;
new_block->size = size;
new_block->free = 0;
new_block->next = NULL;
insert_in_list(new_block);
return (void *)((uintptr_t) new_block + BLOCK_SIZE);
}