1

I'm trying to understand how the placement new/delete works and hence I've written the following program:

# include <iostream>
# include <cstdlib>
using namespace std;

class Test {};
void * operator new (size_t size) throw (std::bad_alloc){
    cout<<"Calling New:"<<endl;
    return new (malloc(size)) Test() ;
}

void operator delete (void *ptr) throw () {
    cout<<"Calling Delete:"<<endl;
    free (ptr) ;
}

int main ()
{
    cout<<"Hello"<<endl;
    Test *ptr = new Test () ;
    delete ptr ;
    return 0;
}

For the above code, I'm getting the below output:

Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling Delete:
Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling New:
Calling Delete:
Hello
Calling New:
Calling Delete:

In the output, it is seen that operator new is called multiple times (even though only one instance of Test is created) and delete is called fewer number of times.

Can anybody please suggest whats wrong here?

Thanks

4
  • 1
    Global operator new should only get and return memory, not call placement new on it. Commented Jul 3, 2013 at 19:30
  • Like aschepler said, return new (malloc(size)) Test() ; this line is horribly wrong, it should be return malloc(size);. Or totally correctly you should echeck for nullptr and throw a bad_alloc Commented Jul 3, 2013 at 19:51
  • @aschepler/Mike: While posting the code I had a doubt in the mind that I'm doing something wrong. Anyways, that calls for another question: how do I initialize the object in that location then? Commented Jul 4, 2013 at 11:39
  • Seems to be problem with the IDE I'm using. Compiled the same in GCC in UNIX and the output is fine. Thanks for your help. Commented Jul 5, 2013 at 11:11

2 Answers 2

3

What is likely happening is that the C++ library uses operator new to allocate memory for its internal purposes. For example, writing to std::cout could well trigger the allocation of some internal buffers, resulting in calls to the overloaded operator new.

Sign up to request clarification or add additional context in comments.

Comments

0

Something is wrong with your compilation:

https://ideone.com/uegedB

Here it is called only once.

The Output is:

Hello
Calling New:
Calling Delete:

Or maybe others things calls it in background.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.