-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvmemalloc.c
More file actions
56 lines (53 loc) · 1.63 KB
/
vmemalloc.c
File metadata and controls
56 lines (53 loc) · 1.63 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
#include "vmemalloc.h"
#include "vmemalloc_large.h"
#include "vmemalloc_small.h"
#define VMEMALLOC_OP "vmemalloc"
#define VMEMFREE_OP "vmemfree"
/* Allocate 'size' bytes of memory. On success the function returns a pointer to
the start of the allocated region. On failure NULL is returned. */
void* vmemalloc(int size) {
if (size <= 0) {
fprintf(stderr, "size passed to vmemalloc was too small (%d)\n", size);
return NULL;
}
void* chunk;
// Treat small chunks differently.
if (size < SMALL_CHUNK_LIMIT) {
chunk = vmemallocSmall(size);
if (chunk == NULL) {
fprintf(stderr, "error in vmemallocSmall(%i)\n", size);
return NULL;
}
} else {
chunk = vmemallocLarge(size);
if (chunk == NULL) {
fprintf(stderr, "error in vmemallocLarge(%d)\n", size);
return NULL;
}
}
allocatedChunkCount++;
outputTraceData(VMEMALLOC_OP);
return chunk;
}
/* Release the region of memory pointed to by 'ptr'. */
void vmemfree(void* ptr) {
if (ptr == NULL) {
fprintf(stderr, "pointer passed to vmemfree was NULL\n");
return;
}
int spaceFreed = vmemfreeSmall(ptr);
if (spaceFreed < 0) {
fprintf(stderr, "error in vmemfreeSmall(%p)\n", ptr);
return;
}
// vmemfreeSmall returns 0 if the chunk is not a small chunk.
if (spaceFreed == 0) {
spaceFreed = vmemfreeLarge(ptr);
if (spaceFreed <= 0) {
fprintf(stderr, "error in vmemfreeLarge(%p)\n", ptr);
return;
}
}
allocatedChunkCount--;
outputTraceData(VMEMFREE_OP);
}