overriding new and delete
So, I'm trying to learn how to do custom memory management for keeping track of used memory, leaks and so forth. I read up and did a simple global override just to test out what I had done. For some reason I seem to be getting recursive calls into the new operator. I'm using MinGW on windows 7.
Here are the three files I'm using.
memManage.h
Code:
#include <exception> // for std::bad_alloc
#include <new>
#include <cstdlib> // for malloc() and free()
#include <list>
#include <iostream> //for debugging
#define DEBUG
namespace MemManage {
extern unsigned long allocated;
extern std::list<void *> addresses;
extern std::list<std::size_t> sizes;
}
void* operator new (std::size_t size)throw ( std::bad_alloc );
void operator delete (void *p) throw ();
memManage.cpp
Code:
#include "memManage.h"
unsigned long MemManage::allocated=0;
std::list<void *> MemManage::addresses;
std::list<std::size_t> MemManage::sizes;
void* operator new (std::size_t size) throw ( std::bad_alloc ) {
#ifdef DEBUG
std::cout<<"\tallocating\n";
#endif
void *p=malloc(size);
if (p==0)
throw std::bad_alloc();
#ifdef DEBUG
std::cout<<"\t\tpassed first exception\n";
#endif
MemManage::allocated+=size;
if(MemManage::allocated<0) {
throw std::bad_alloc();
}
else {
MemManage::addresses.push_back(p);
MemManage::sizes.push_back(size);
}
#ifdef DEBUG
std::cout<<"\tallocated\n";
#endif
return p;
}
void operator delete (void *p) throw () {
std::list<void*>::iterator aIt=MemManage::addresses.begin();
std::list<std::size_t>::iterator sIt=MemManage::sizes.begin();
bool deleted=false;
for(;aIt != MemManage::addresses.end();) {
if((*aIt) == p) {
deleted=true;
MemManage::allocated-=*sIt;
MemManage::addresses.erase(aIt);
MemManage::sizes.erase(sIt);
}
if(deleted) {
aIt=MemManage::addresses.end();
}
else {
aIt++;
sIt++;
}
}
if(!deleted){throw std::bad_alloc();}
free(p);
}
memTest.cpp
Code:
#include <iostream>
#include <list>
#include "memManage.h"
using namespace std;
int main(int argc, char* argv[]) {
cout<<MemManage::allocated<<"\n";
int* test;
test=new int[10];
cout<<MemManage::allocated<<"\n";
delete[] test;
cout<<MemManage::allocated<<"\n";
return 0;
}
And here is my abridged output
Code:
0
allocating
passed first exception
allocating
passed first exception
allocating
passed first exception
.
.
.
.
.
allocating
passed first exception
allocating
passed first exception
crash