Memory Counter


Home --> Programming Projects --> FPS Game Code --> Memory Code --> Memory Counter

The Goal

The goal is to be able to track how much memory has been allocated/deallocated in a C++ program.

How We Do It

We use this method. That is, we overload the global C++ new and delete operators. Also, we have our new operator allocate an additional 4 bytes of memory before the actual allocation, and in those 4 bytes we will store the size of the allocation. This way, the delete operator knows the size of memory we are deallocating.

Our method is slightly different from that link because we store the number of bytes in a 4 byte integer instead of something larger.

We then have an "atomic" (to make it thread safe) to store the total number of bytes the program has allocated.

The Code

#include <atomic>

std::atomic_int64_t g_total_bytes_used = 0;

//The size is the number of bytes.
void * operator new(size_t size) {
    g_total_bytes_used += (long long)size;
    uint32_t * p = (uint32_t *)malloc(size + sizeof(uint32_t));
    p[0] = size;           //Store the size in the first few bytes.
    return (void*)(&p[1]); //Return the memory just after the size we stored.
}

void operator delete(void * ptr) {
    uint32_t * p = (uint32_t*)ptr; //Make the pointer the right type.
    size_t size = p[-1];         //Get the data we stored at the beginning of this block.
    g_total_bytes_used -= (long long)size;
    void * p2 = (void*)(&p[-1]); //Get a pointer to the memory we originally really allocated.
    free(p2);                    //Free it.
}