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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
/*
# This file is part of libkd.
# Licensed under a 3-clause BSD style license - see LICENSE
*/
#include <stdlib.h>
#include <string.h>
#include "kdtree_mem.h"
static int memory_total = 0;
// Are we tracking memory usage by libkd?
#if defined(KDTREE_MEM_TRACK)
struct memblock {
int nbytes;
};
typedef struct memblock memblock;
void* MALLOC(size_t sz) {
memblock* mb;
if (!sz) return NULL;
mb = (memblock*)malloc(sz + sizeof(memblock));
mb->nbytes = sz;
memory_total += sz;
return mb + 1;
}
void* CALLOC(size_t nmemb, size_t sz) {
char* ptr = MALLOC(nmemb * sz);
memset(ptr, 0, nmemb * sz);
return ptr;
}
void* REALLOC(void* ptr, size_t sz) {
memblock* mb;
if (!ptr) {
return MALLOC(sz);
}
if (!sz) {
FREE(ptr);
return NULL;
}
mb = ptr;
mb--;
memory_total += (sz - mb->nbytes);
mb->nbytes = sz;
mb = realloc(mb, sz + sizeof(memblock));
return mb + 1;
}
void FREE(void* ptr) {
memblock* mb;
int nfreed;
if (!ptr) return;
mb = ptr;
mb--;
nfreed = mb->nbytes;
memory_total -= nfreed;
free(mb);
}
#endif
// Is memory-tracking enabled?
int kdtree_mem_enabled() {
#if defined(KDTREE_MEM_TRACK)
return 1;
#else
return 0;
#endif
}
// Reset the memory usage counter
void kdtree_mem_reset() {
memory_total = 0;
}
// Get the current memory usage
int kdtree_mem_get() {
return memory_total;
}
|