jacob-tate
12/4/2019 - 6:04 AM

Overload the new and delete operators globally

/*! 
 *  @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);
}