overloading the global operator new

Discussion in 'C++' started by Zachary Turner, Dec 10, 2004.

  1. I'm having trouble overloading the global operator new and delete. I
    want to do this for debugging purposes to trace allocations and
    deallocations. What I have is

    #ifdef _DEBUG
    // User-defined operator new.
    void *operator new( size_t stAllocateBlock )
    {
    static fInOpNew = 0; // Guard flag.

    if ( fLogMemory && !fInOpNew )
    {
    fInOpNew = 1;
    clog << "Memory block " << ++cBlocksAllocated
    << " allocated for " << stAllocateBlock
    << " bytes\n";
    fInOpNew = 0;
    }

    return malloc( stAllocateBlock );
    }

    // User-defined operator delete.
    void operator delete( void *pvMem )
    {
    static fInOpDelete = 0; // Guard flag.
    if( fLogMemory && !fInOpDelete )
    {
    fInOpDelete = 1;
    clog << "Memory block " << cBlocksAllocated--
    << " deallocated\n";
    fInOpDelete = 0;
    }

    free( pvMem );
    }
    #endif

    (copied directly from microsoft help file just to make sure there's no
    syntax errors preventing compilation)

    I put this in a regular C++ source file but I get compilation errors.

    c:\develop\BrowseBuddy\Memory.cpp(7) : error C2084: function 'void
    *operator new(size_t)' already has a body
    predefined C++ types (compiler internal)(20) : see previous
    definition of 'new'


    I'm using VC++ 7 compiler. Anybody have any idea where I might be
    going wrong?

    Thanks
    Zachary Turner, Dec 10, 2004
    #1
    1. Advertising

  2. On 10 Dec 2004 13:35:30 -0800, "Zachary Turner" <>
    wrote:

    >I'm having trouble overloading the global operator new and delete. I
    >want to do this for debugging purposes to trace allocations and
    >deallocations. What I have is
    >
    >#ifdef _DEBUG
    >// User-defined operator new.
    >void *operator new( size_t stAllocateBlock )


    You might not exactly get what you want, but you could try declaring the
    procedure as static, and including the piece of code in all files.
    Raymond Martineau, Dec 11, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Tim Milstead
    Replies:
    0
    Views:
    5,107
    Tim Milstead
    Apr 20, 2004
  2. Robert Wierschke
    Replies:
    3
    Views:
    11,057
    Louise56
    Aug 3, 2004
  3. John Smith
    Replies:
    2
    Views:
    413
    Ivan Vecerina
    Oct 6, 2004
  4. TuxC0d3
    Replies:
    6
    Views:
    1,617
    John Carson
    Dec 6, 2005
  5. Replies:
    11
    Views:
    720
    James Kanze
    May 16, 2007
Loading...

Share This Page