New operator overloading causes Infinite recursion when inserting the address in a map
<p>I am overloading the new operator to write my own custom memory monitoring class which has a map of address to bytes.</p>

<p>but unfortunately when I insert the address of the memory to a map, the map will create a new object and the overloaded new operator will get called again and creates a infinite recursion and memory leak.</p>

<p>I have added the code that causes the issue below.
Please advice.</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;cstdlib&gt;
#include &lt;map&gt;


using namespace std;
class MemoryManager{ 
  static map&lt;void* const, size_t&gt; memory;  //void* is an address, size_t is size
  static void allocate(void* ptr, size_t size);
}

void MemoryManager::allocate(void* ptr, size_t size){
   cout &lt;&lt; ptr &lt;&lt; endl; // prints the address

   // inserts the address of the memory in a map.
   // the compiler will create `new` object and creates a recursion.
   // infinite recursion is created.
   memory.insert(pair&lt;void* const, size_t&gt;(ptr, size));

   totalBytes += size;

   number_of_allocations++;

}


void* operator new (size_t size){

  void* ptr = malloc(size);

  MemoryManager::allocate(ptr, size);

  return ptr;
}




int main(){


   int* p1 = new int;

}
</code></pre>