track C++ memory allocations

前端 未结 8 1862
执笔经年
执笔经年 2020-11-28 04:18

I am looking for a way to track memory allocations in a C++ program. I am not interested in memory leaks, which seem to be what most tools are trying to find, but r

8条回答
  •  一生所求
    2020-11-28 04:28

    For a generic C++ memory tracker you will need to overload the following:

    global operator new
    global operator new []
    global operator delete
    global operator delete []
    any class allocators
    any in-place allocators
    

    The tricky bit is getting useful information, the overloaded operators only have size information for allocators and memory pointers for deletes. One answer is to use macros. I know. Nasty. An example - place in a header which is included from all source files:

    #undef new
    
    void *operator new (size_t size, char *file, int line, char *function);
    // other operators
    
    #define new new (__FILE__, __LINE__, __FUNCTION__)
    

    and create a source file with:

    void *operator new (size_t size, char *file, int line, char *function)
    {
      // add tracking code here...
      return malloc (size);
    }
    

    The above only works if you don't have any operator new defined at class scope. If you do have some at class scope, do:

    #define NEW new (__FILE__, __LINE__, __FUNCTION__)
    

    and replace 'new type' with 'NEW type', but that requires changing a lot of code potentially.

    As it's a macro, removing the memory tracker is quite straightforward, the header becomes:

    #if defined ENABLED_MEMORY_TRACKER
    #undef new
    
    void *operator new (size_t size, char *file, int line, char *function);
    // other operators
    
    #define NEW new (__FILE__, __LINE__, __FUNCTION__)
    #else
    #define NEW new
    #endif
    

    and the implementation file:

    #if defined ENABLED_MEMORY_TRACKER
    void *operator new (size_t size, char *file, int line, char *function)
    {
      // add tracking code here...
      return malloc (size);
    }
    endif
    

提交回复
热议问题