hammer/src/system_allocator.c

32 lines
818 B
C
Raw Normal View History

2013-04-26 20:36:54 -07:00
#include <string.h>
#include <stdlib.h>
2012-10-10 15:58:03 +02:00
#include "internal.h"
static void* system_alloc(HAllocator *allocator, size_t size) {
2013-04-26 20:36:54 -07:00
void* ptr = calloc(size + sizeof(size_t), 1);
*(size_t*)ptr = size;
return ptr + sizeof(size_t);
2012-10-10 15:58:03 +02:00
}
static void* system_realloc(HAllocator *allocator, void* ptr, size_t size) {
2013-04-26 20:36:54 -07:00
if (ptr == NULL)
return system_alloc(allocator, size);
ptr = realloc(ptr - sizeof(size_t), size + sizeof(size_t));
size_t old_size = *(size_t*)ptr;
*(size_t*)ptr = size;
if (size > old_size)
memset(ptr+sizeof(size_t)+old_size, 0, size - old_size);
return ptr + sizeof(size_t);
2012-10-10 15:58:03 +02:00
}
static void system_free(HAllocator *allocator, void* ptr) {
2013-04-26 20:36:54 -07:00
free(ptr - sizeof(size_t));
2012-10-10 15:58:03 +02:00
}
HAllocator system_allocator = {
.alloc = system_alloc,
.realloc = system_realloc,
.free = system_free,
};