This example demonstrates using of custom memory allocators.In this case allocator works as a memory checker, counts number of allocations and deallocations to make sure that there is no memory leaks.
#include <iostream>
#include <cassert>
using namespace std;
{
public:
static unsigned na_;
static unsigned nf_;
static bm::word_t* allocate(
size_t n,
const void *)
{
++na_;
assert(n);
*p = (unsigned)n;
return ++p;
}
{
++nf_;
--p;
::free(p);
}
static int balance()
{
return int(nf_ - na_);
}
};
{
public:
static unsigned na_;
static unsigned nf_;
static void* allocate(size_t n, const void *)
{
++na_;
assert(sizeof(size_t) == sizeof(void*));
void* p = ::malloc((n+1) * sizeof(void*));
size_t* s = (size_t*) p;
*s = n;
return (void*)++s;
}
static void deallocate(void* p, size_t )
{
++nf_;
size_t* s = (size_t*) p;
--s;
::free(s);
}
static int balance()
{
return int(nf_ - na_);
}
};
typedef
{
try
{
{
bv[10] = true;
bv[100000] = true;
bv[10000000] = false;
}
}
catch(std::exception& ex)
{
std::cerr << ex.what() << std::endl;
return 1;
}
return 0;
}