How to use the new operator to count the number of times for a heap allocation

Given the following code:

int i;
...
ostingstream os;
os<<i;
string s=os.str();

      

I want to count the number of times heap allocation when used ostringstream

this way. How can i do this? Maybe through operator new

?

Thank.

+3


source to share


3 answers


Yes, and here's how you could do it:

#include <new>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

int number_of_allocs = 0;

void* operator new(std::size_t size) throw(std::bad_alloc) {
  ++number_of_allocs;
  void *p = malloc(size);
  if(!p) throw std::bad_alloc();
  return p;
}

void* operator new  [](std::size_t size) throw(std::bad_alloc) {
  ++number_of_allocs;
  void *p = malloc(size);
  if(!p) throw std::bad_alloc();
  return p;
}

void* operator new  [](std::size_t size, const std::nothrow_t&) throw() {
  ++number_of_allocs;
  return malloc(size);
}
void* operator new   (std::size_t size, const std::nothrow_t&) throw() {
  ++number_of_allocs;
  return malloc(size);
}


void operator delete(void* ptr) throw() { free(ptr); }
void operator delete (void* ptr, const std::nothrow_t&) throw() { free(ptr); }
void operator delete[](void* ptr) throw() { free(ptr); }
void operator delete[](void* ptr, const std::nothrow_t&) throw() { free(ptr); }

int main () {
  int start(number_of_allocs);

  // Your test code goes here:
  int i(7);
  std::ostringstream os;
  os<<i;
  std::string s=os.str();
  // End of your test code

  int end(number_of_allocs);

  std::cout << "Number of Allocs: " << end-start << "\n";
}

      

In my environment (Ubuntu 10.4.3, g ++) the answer is "2".




EDIT : Quoting MSDN

A new global operating function is called when a new operator is used to allocate objects of built-in types, objects of class type that do not contain new user-defined operator functions, and arrays of any type. When a new operator is used to allocate objects of a class type where operator new is defined, that class operator new is called.

This way, every new expression will call the global one operator new

, unless the class exists operator new

. For the classes you listed, I believe there is no class operator new

.

+5


source


If you want to count dynamically allocated objects, you must replace the operator new

for your class by overloading it and adding the counting logic there.



Good Read: How am I supposed to write ISO C ++ standard ISO compliant and remote statements?

+1


source


If you are using Linux (glibc) you can use the malloc hook to register all heap allocations.

0


source







All Articles