A virtual currency betting bot for Twitch chat. https://ddark.net/better
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
better/src/better_alloc.cpp

106 lines
2.5 KiB

#pragma warning (disable: 4200) // nonstandard extension used: zero-sized array in struct/union
#include "better_alloc.h"
#include "better_App.h"
extern "C"
{
#include "ost.h"
}
#include <cstdlib>
#include <cstring>
#include <cassert>
extern App app;
#if BETTER_DEBUG
static int comp(const void* l, const void* r)
{
AllocSum *lp = (AllocSum*)l, *rp = (AllocSum*)r;
return strcmp(lp->strid, rp->strid);
}
void* tracked_malloc(size_t size, const char* strid)
{
if (app.global_alloc_map == NULL)
{
app.global_alloc_map = (ost*) malloc(sizeof(ost));
ost_init(app.global_alloc_map, comp, malloc, free);
}
AllocHeader* h = (AllocHeader*)malloc(sizeof(AllocHeader)+size);
h->size = size;
h->strid = _strdup(strid);
AllocSum* key = (AllocSum*)malloc(sizeof(AllocSum));
key->strid = strid;
ost_node* node = ost_find(app.global_alloc_map, key);
if (node == NULL)
{
key->size = size;
key->count = 1;
ost_insert(app.global_alloc_map, key);
}
else
{
free(key);
((AllocSum*)node->data)->size += size;
((AllocSum*)node->data)->count += 1;
}
return h+1;
}
void tracked_free(void* ptr)
{
AllocHeader* h = ((AllocHeader*)ptr)-1;
AllocSum* key = (AllocSum*)malloc(sizeof(AllocSum));
key->strid = h->strid;
ost_node* node = ost_find(app.global_alloc_map, key);
if (node == NULL || ((AllocSum*)node->data)->size < h->size || ((AllocSum*)node->data)->count < 1)
assert(false);
else
{
free(key);
((AllocSum*)node->data)->size -= h->size;
((AllocSum*)node->data)->count -= 1;
}
free(h->strid);
free(h);
}
void* tracked_realloc(void* ptr, size_t size, const char* strid)
{
if (ptr == NULL)
return tracked_malloc(size, strid);
if (app.global_alloc_map == NULL)
{
app.global_alloc_map = (ost*) malloc(sizeof(ost));
ost_init(app.global_alloc_map, comp, malloc, free);
}
AllocHeader* h = ((AllocHeader*)ptr)-1;
h = (AllocHeader*)realloc(h, sizeof(AllocHeader)+size);
AllocSum* key = (AllocSum*)malloc(sizeof(AllocSum));
key->strid = h->strid;
ost_node* node = ost_find(app.global_alloc_map, key);
if (node == NULL || ((AllocSum*)node->data)->size < h->size || ((AllocSum*)node->data)->count < 1)
assert(false);
else
{
free(key);
((AllocSum*)node->data)->size -= h->size;
((AllocSum*)node->data)->size += size;
}
h->size = size;
return h+1;
}
#endif // BETTER_DEBUG