Macro to replace C++ operator new

后端 未结 7 1803
臣服心动
臣服心动 2020-12-04 13:47

Is it possible to create macros to replace all forms of operator new with overloads that include additional args...say __FILE__ and __LINE__<

相关标签:
7条回答
  • 2020-12-04 14:02

    Here is what I use:

    In new.cpp

    const char* __file__ = "unknown";
    size_t __line__ = 0;
    
    void* operator new(size_t size) {
        void *ptr = malloc(size);
        record_alloc(ptr,__file__,__line__);
        __file__ = "unknown";
        __line__ = 0;
        return ptr;
    }
    
    void delete(void *ptr)
    {
       unrecord_alloc(ptr);
       free(ptr);
    }
    

    For compactness, I'm leaving out the other definitions of new and delete. "record_alloc" and "unrecord_alloc" are functions that maintain a linked list of structure containing ptr, line, and file).

    in new.hpp

    extern const char* __file__;
    extern size_t __line__;
    #define new (__file__=__FILE__,__line__=__LINE__) && 0 ? NULL : new
    

    For g++, "new" is expanded only once. The key is the "&& 0" which makes it false and causes the real new to be used. For example,

    char *str = new char[100];
    

    is expanded by the preprocessor to

    char *str = (__file__="somefile.c",__line__=some_number) && 0 ? NULL : new char [100];
    

    Thus file and line number are recorded and your custom new function is called.

    This works for any form of new -- as long as there is a corresponding form in new.cpp

    0 讨论(0)
  • 2020-12-04 14:04

    No, there's no way.

    You could do this in the bad old days of malloc()/free() but not for new.

    You can replace the memory allocator by globally overriding the new operator, but you cannot inject the special variables you're talking about.

    0 讨论(0)
  • 2020-12-04 14:06

    You should check out this excellent blog entry by my coworker Calvin. We had a situation recently where we wanted to enable this type of fix in order to associate memory leaks with the line that allocated them in diagnostic/debug builds. It's an interesting trick

    https://docs.microsoft.com/en-us/archive/blogs/calvin_hsia/overload-operator-new-to-detect-memory-leaks

    0 讨论(0)
  • 2020-12-04 14:14

    You don't say what compiler you are using, but at least with GCC, you can override new and log the caller address, then later translate that to file/line information with addr2line (or use the BFD library to do that immediately).

    0 讨论(0)
  • 2020-12-04 14:14

    What you could do is to overload the operator new and get the stack trace there (platform specific) and use the stack information to deduce from where new was called.

    0 讨论(0)
  • 2020-12-04 14:18

    I found the following library "nvwa" very useful for tracking down new/delete memory leaks - have a look at the file "debug_new" for examples, or just use it 'as is'.

    0 讨论(0)
提交回复
热议问题