-
Notifications
You must be signed in to change notification settings - Fork 3
/
SWalloc.h
38 lines (28 loc) · 825 Bytes
/
SWalloc.h
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
#ifndef SW_ALLOC_H
#define SW_ALLOC_H
#include <assert.h>
#include <stdint.h>
static inline void* sw_aligned_malloc(size_t size, size_t alignment) {
assert(alignment > sizeof(void *));
size_t space = size + (alignment - 1);
void *ptr = malloc(space + sizeof(void *));
void *original_ptr = ptr;
char *ptr_bytes = (char *)ptr;
ptr_bytes += sizeof(void *);
size_t off = (size_t)((uintptr_t)(ptr_bytes) % alignment);
if (off) {
off = alignment - off;
}
ptr_bytes += off;
assert(((uintptr_t)(ptr_bytes) % alignment) == 0);
ptr = ptr_bytes;
ptr_bytes -= sizeof(void *);
memcpy(ptr_bytes, &original_ptr, sizeof(void *));
return ptr;
}
static inline void sw_aligned_free(void* p) {
if (p) {
free(((void **)p)[-1]);
}
}
#endif // SW_ALLOC_H