Dynamic Memory and the Free Store

Writing a memory manager

Can I write my own memory manager to replace new and delete?

Abstract art representing computer programming

Yes, it is possible to write your own memory manager to replace the default new and delete operators.

In C++, you can overload the new and delete operators globally, or for a specific class. When you do this, your custom versions will be called instead of the default ones.

Here's a simple example of a global overload:

#include <cstdlib>
#include <iostream>

void* operator new(size_t size) {
  std::cout << "Allocating " << size << " bytes\n";
  return std::malloc(size);
}

void operator delete(void* ptr) noexcept {
  std::cout << "Freeing memory\n";
  std::free(ptr);
}

int main() {
  int* ptr = new int(10);
  delete ptr;
}
Allocating 4 bytes
Freeing memory

In this example, we're simply forwarding to malloc and free, but you could implement your own memory management strategy.

You might want to do this for various reasons:

  1. You need to track memory allocations for debugging purposes.
  2. You want to optimize memory allocation for your specific use case.
  3. You're working in an embedded environment with no default memory management.

However, writing a correct and efficient memory manager is a complex task. It involves understanding low-level details of how memory works and dealing with issues like fragmentation and concurrency.

In most cases, the default memory manager is sufficient, and if you need more control, you can use proven libraries like jemalloc or tcmalloc.

Additionally, in modern C++, the need for custom memory management is reduced by the use of smart pointers and standard containers, which handle much of the memory management burden for you.

So while it's possible and sometimes necessary to write your own memory manager, it's not something to undertake lightly, and in many cases, there are better solutions.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved