1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Placement new - memory leak?

Discussion in 'C++' started by IvesRogne, Sep 9, 2010.

  1. IvesRogne

    IvesRogne New Member

    Sep 9, 2010
    Likes Received:
    Trophy Points:
    Hi everyone,

    Let's say I have a base class A, and two derived classes B::A and C::A, such that sizeof(A) < sizeof(B) < sizeof(C).

    In a parsing routine I need to obtain a pointer to an A object which will be constructed later (since the constructor parameters are not available yet).

    So I simply allocate the memory and defer the construction to later. The problem is this A object could turn out to be a B or a C, I have no way to know. Hence I allocate the memory to cover the worst case (C).

    A* a = static_cast( ::operator new(sizeof(C)) );
    When the parameters become available, I construct the object using placement new. Notice that some bytes may be left unused if I instantiate a B instead of a C.

    a = new (a) B(...params...);
    When the object is no longer needed I simply delete it, as per usual. My hope is that the destructor is adequately called and the allocated memory is released.

    delete a;
    So I'd have two questions:
    - Does deleting directly a B object causes a memory leak, or does it free the entire sizeof(C) patch of memory?
    - Is this a safe/recommended practice (i.e. are there some better workarounds)?

  2. techgeek.in

    techgeek.in New Member

    Dec 20, 2009
    Likes Received:
    Trophy Points:
    EOC (exploitation of computers)..i m a Terminator.
    Not an alien!! for sure
    Home Page:
    All you have to do is make sure you have allocated enough memory for the object......
    You don't need placement-new to demonstrate this. In many "debugging" versions of run-time libraries, a call to malloc() or new[] allocates extra "guard" bytes to detect memory overwrites and corruption.....
    So for example, a "malloc(10)" or a "new char[10]", need not just allocate 10 bytes. You are guaranteed at least 10 bytes were allocated, but nothing stops an implementation from allocating more.....

Share This Page