-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmart_allocation.c
More file actions
41 lines (30 loc) · 832 Bytes
/
smart_allocation.c
File metadata and controls
41 lines (30 loc) · 832 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdlib.h>
#include <stdio.h>
#include "hashmap.h"
#include "smart_allocation.h"
struct hashmap_t *hashmap = NULL;
void* smart_malloc(size_t size) {
if(!hashmap) hashmap = hashmap_create(SMART_ALLOCATOR_SIZE);
void *ptr = malloc(size);
hashmap_put(hashmap, (u_int64_t)ptr % SMART_ALLOCATOR_SIZE, ptr);
return ptr;
}
int smart_free(void *ptr) {
if(!hashmap) return 0;
if(!hashmap_remove(hashmap, (u_int64_t)ptr % SMART_ALLOCATOR_SIZE)) return 0;
free(ptr);
return 1;
}
void smart_deallocate() {
if(!hashmap) return;
for(int i = 0; i < hashmap->size; i++) {
struct hashmap_bucket_t *bucket = hashmap->buckets[i];
struct hashmap_entry_t *entry = bucket->entry;
while(entry) {
struct hashmap_entry_t *next = entry->next;
free(entry->value);
entry = next;
}
}
hashmap_destroy(hashmap);
}