Skip to content

Instantly share code, notes, and snippets.

@Jacob-Tate
Created December 4, 2019 06:04
Show Gist options
  • Save Jacob-Tate/c76c943e064da84b3c8852120792330a to your computer and use it in GitHub Desktop.
Save Jacob-Tate/c76c943e064da84b3c8852120792330a to your computer and use it in GitHub Desktop.
/*!
* @file crtp_allocation.cpp
* @brief Overriding the new and delete operators globally
* @author Jacob I. Tate
* @version 0.0.1
* @date 2019
*/
#include <cstdlib>
#include <malloc.h>
/**
* @brief Allocates the given amount of memory
*
* @param bytes The amount of bytes to allocate
* @return void* The pointer to the allocated memory
*/
void *operator new(decltype(sizeof(0)) bytes)
{
void *ptr = malloc(bytes);
return ptr;
}
/**
* @brief Deallocate at @a ptr
*
* @param ptr The pointer to deallocate
*/
void operator delete(void *ptr) noexcept
{
#if defined(_WIN32)
std::size_t ptr_size = _msize(ptr);
#else
std::size_t ptr_size = malloc_usable_size(ptr);
#endif
// TODO: Do something with the size we are deallocating
free(ptr);
}
/**
* @brief Allocates the given amount of memory
*
* @param bytes The amount of bytes to allocate
* @return void* The pointer to the allocated memory
*/
void *operator new[](decltype(sizeof(0)) bytes)
{
void *ptr = malloc(bytes);
return ptr;
}
/**
* @brief Deallocate an array at @a ptr
*
* @param ptr The pointer to an array to deallocate
*/
void operator delete[](void *ptr) noexcept
{
#if defined(DP_OS_FAMILY_WINDOWS)
std::size_t ptr_size = _msize(ptr);
#else
std::size_t ptr_size = malloc_usable_size(ptr);
#endif
// TODO: Do something with the size we are deallocating
free(ptr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment