Hi all,

I have implemented overloaded function for operator new. In this function I have not allocated any memory still while exiting from program it is getting crashed.
Code is as below:
class A
{
public:
int a;
int b;
A()
{
cout<<"Inside A::A()"<<endl;
}
void* operator new(size_t s)
{
cout<<s<<endl;
cout<<"Inside A::new()"<<endl;

}

};
int main(int argc, char argv[])
{
A
a= new A;
system("PAUSE");
return EXIT_SUCCESS;
}

Output of program is -
8
Inside A::new()
Inside A::A()
Crash

The problem is (as far as I can tell) that you are getting caught by garbage cleanup of some kind. You created an A but it doesnt have a memory space (since new didnt return one) as such when the program ends the operating system tries to automatically destroy a, by calling a default destructor on it that it defined itself. Since A contains two integers, the destructor probably automatically deletes them. The issue is that there is no a to destroy because new never returned one. As such an attempt to delete A results in a crash. Also new returns a pointer and is meant to be used on pointers. Here is an example:

A a();//construct a 'real' A
A *newA=new A;//construct a 'pointer' A

Of course I have been know to be completely wrong before, but I think I am more than less correct this time. :P

A a = new A() should produce a compile-time error. You can not assign a pointer to a non-pointer type like that.
You probably meant A *a = new A(). At that point your pointer is just some random memory location. Unless you try to delete it you should not have any problems. Something tells me that you have not produced the exact code you are dealing with ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.