Use atomics for allocation counter
I was getting cases where the CPU cache was causing issues with the allocation counter, for the longest time I thought I was doing something wrong, but when the allocation counter went below 0, I realized it was because I didn't use atomics for incrementing/decrementing the allocation counter variable. The allocation counter now always should have the correct value.
This commit is contained in:
parent
906535022f
commit
fd24d0de2f
@ -18,6 +18,7 @@
|
||||
#include <string.h>
|
||||
#include "base.h"
|
||||
#include "bmem.h"
|
||||
#include "threading.h"
|
||||
|
||||
/*
|
||||
* NOTE: totally jacked the mem alignment trick from ffmpeg, credit to them:
|
||||
@ -84,7 +85,7 @@ static void a_free(void *ptr)
|
||||
}
|
||||
|
||||
static struct base_allocator alloc = {a_malloc, a_realloc, a_free};
|
||||
static uint64_t num_allocs = 0;
|
||||
static long num_allocs = 0;
|
||||
|
||||
void base_set_allocator(struct base_allocator *defs)
|
||||
{
|
||||
@ -100,14 +101,14 @@ void *bmalloc(size_t size)
|
||||
bcrash("Out of memory while trying to allocate %lu bytes",
|
||||
(unsigned long)size);
|
||||
|
||||
num_allocs++;
|
||||
os_atomic_inc_long(&num_allocs);
|
||||
return ptr;
|
||||
}
|
||||
|
||||
void *brealloc(void *ptr, size_t size)
|
||||
{
|
||||
if (!ptr)
|
||||
num_allocs++;
|
||||
os_atomic_inc_long(&num_allocs);
|
||||
|
||||
ptr = alloc.realloc(ptr, size);
|
||||
if (!ptr && !size)
|
||||
@ -122,11 +123,11 @@ void *brealloc(void *ptr, size_t size)
|
||||
void bfree(void *ptr)
|
||||
{
|
||||
if (ptr)
|
||||
num_allocs--;
|
||||
os_atomic_dec_long(&num_allocs);
|
||||
alloc.free(ptr);
|
||||
}
|
||||
|
||||
uint64_t bnum_allocs(void)
|
||||
long bnum_allocs(void)
|
||||
{
|
||||
return num_allocs;
|
||||
}
|
||||
|
@ -39,7 +39,7 @@ EXPORT void bfree(void *ptr);
|
||||
|
||||
EXPORT int base_get_alignment(void);
|
||||
|
||||
EXPORT uint64_t bnum_allocs(void);
|
||||
EXPORT long bnum_allocs(void);
|
||||
|
||||
EXPORT void *bmemdup(const void *ptr, size_t size);
|
||||
|
||||
|
@ -233,7 +233,6 @@ int main(int argc, char *argv[])
|
||||
blog(LOG_ERROR, "%s", error);
|
||||
}
|
||||
|
||||
blog(LOG_INFO, "Number of memory leaks: %llu",
|
||||
(unsigned long long int)bnum_allocs());
|
||||
blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
|
||||
return ret;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user