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
int a;
int b;
cout<<"Inside A::A()"<<endl;
void* operator new(size_t s)
cout<<"Inside A::new()"<<endl;


int main(int argc, char argv[])
a= new A;

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

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 ...

Edited 4 Years Ago by L7Sqr

This article has been dead for over six months. Start a new discussion instead.