Overriding "new" and logging caller data

I am trying to write a memory profiler, and so far I have managed to get my custom functions to work for malloc, free, new and delete. I tried to use __FILE__it __LINE__to register the sender inside the overloaded new method, but (as expected) it just gives information about where the overloaded function is located. Is there a way to get details about the initiator for overloaded functions without any changes to the existing code of the component under test (for example, #define for malloc)?

Function I use:

void* operator new (size_t size)
{
    if(b_MemProfStarted)
    {
        b_MemProfStarted = false;
        o_MemLogFile << "NEW: " << "| Caller: "<< __FILE__ << ":"
                << __LINE__ << endl;
        b_MemProfStarted = true;
    }

    void *p=malloc(size);
    if (p==0) // did malloc succeed?
    throw std::bad_alloc(); // ANSI/ISO compliant behavior

    return p;
}

bool b_MemProfStarted is used to avoid recursive calls to onstream and map.insert.

+5
2

new(foo, bar) MyClass;

void*operator new(std::size_t, Foo, Bar){
    ...
}

new(__LINE__, __FILE__) MyClass;

void*operator new(std::size_t, unsigned line, const char*file){
    ...
}

#define new new(__LINE__, __FILE__)

, .

, , , . . , .

+3

,

#define new new(__FILE__, __LINE__)

:

#define DEBUG_NEW new(__FILE__, __LINE__)
#define new DEBUG_NEW

: http://sourceforge.net/projects/nvwa/

0

All Articles