How to use the new operator to count the number of times for a heap allocation
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
.
source to share
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?
source to share
If you are using Linux (glibc) you can use the malloc hook to register all heap allocations.
source to share