overloaded new operator

Started by
4 comments, last by Evil Steve 18 years ago
Why is my code crashing??

#include <iostream>
using namespace std;

void * operator new(size_t size)
	{
	cout<<"Overloaded New Called";
	void *p=malloc(size);
	if(!p)
		cout<<"Memory Can Not Be Allocated";

	return p;
	}

int main()
{

char*p=new char;
return 0;
}



Advertisement
c++ iostream functions are very likely to need to allocate memory when you use them, and using them inside operator new will probably cause a stack overflow. If you need to print inside operator new, some options are:

- Use printf
- Use OutputDebugString on Windows
- Add guards to prevent operator new from being recursively called (only log when operator new is one level deep). Be careful to make it threadsafe.
Continuing on what the above poster mentioned, globally overloading the 'new' operator is usually not a good thing to do. You're going to run into more headaches than just this when you try including standard headers and you get 'new' clashes.

Depending on what you're using this for, you can create some base class that has it's own overloaded new operator. All classes derived from this base class will use base::new, but base::new itself could use the standard new operator. With this you can cout to your hearts content.

Or you could look into an existing memory manager implementation (Fluid Studios, or the one that has been floating around these forums for the past week). Fluid Studios is the one I have used extensively. It does manage to overload the global new operator, but as a comment in it's source code says: "Kids, please don't try this at home. We're trained professionals here." :)
Modifying my code

#include <iostream>#include <cstdio>using namespace std;void * operator new(size_t size){	printf("Overloaded New Called\n");	void *p=malloc(size);	if(!p)		cout<<"Memory can not be allocated";		return p;}void operator delete(void *q){	free(q);	}int main(){int*p=new int;return 0;}


Now output is
Overloaded New Called
Overloaded New Called
Overloaded New Called
operator new should throw a std::bad_alloc when it is unable to allocate memory (using cout is probably unwise as well :) If you're suprised that operator new is called multiple times, then put a breakpoint in there and see exactly where it is being called from. It's not just your own code that uses it :)

I don't like Fluid Studio's library since it #define's new, but I agree with Doggan that you shouldn't overload the normal operator new yourself until you're quite familiar with C++ and you know all the consequences.
Use the debugger - that's what it's for [smile] If you don't know how to use it, there's a few resources around on the Internet, or oyu could just play with it (which is what I did) and see what you come up with.

This topic is closed to new replies.

Advertisement