user1096734
user1096734

Reputation:

How to use operator new to count number of times of dynamic memory allocation

Given the following code:

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

I want to count the number of times of dynamic memory allocation when using ostringstream this way. How can I do that? Maybe through operator new?

Thank you.

Upvotes: 4

Views: 3518

Answers (3)

Robᵩ
Robᵩ

Reputation: 168716

Yes, and here is 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

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

So every new-expression will invoke the global operator new, unless there is a class operator new. For the classes you listed, I believe that there is no class-level operator new.

Upvotes: 7

doron
doron

Reputation: 28902

If you are using Linux (glibc), you can use a malloc hook to log all dynamic memory allocation.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206566

If you want to count the dynamically allocated objects, You should replace the new operator for your class by overloading it and add the counting logic in there.

Good Read:
How should I write ISO C++ Standard conformant custom new and delete operators?

Upvotes: 1

Related Questions