跟踪每个功能的内存分配

Track memory allocation per function

本文关键字:内存 分配 功能 跟踪      更新时间:2023-10-16

所以我知道我可以跟踪内存分配的方法,例如:http://www.almostinfinite.com/memtrack.html

但是,我想知道是否有一个很好的方法可以通过每个功能进行此操作,以便我可以报告每个功能分配多少。现在,我可以获取文件和行,以及类型ID在我提供的链接中,但我想找到最多的功能。

做什么像:http://ideone.com/wqjkrw

#include <iostream>
#include <cstring>
class MemTracker
{
    private:
        static char func_name[100];
        static size_t current_size;
    public:
        MemTracker(const char* FuncName) {strcpy(&func_name[0], FuncName);}
        static void inc(size_t amount) {current_size += amount;}
        static void print() {std::cout<<func_name<<" allocated: "<<current_size<<" bytes.n";}
        static void reset() {current_size = 0; memset(&func_name[0], 0, sizeof(func_name)/sizeof(char));}
};
char MemTracker::func_name[100] = {0};
size_t MemTracker::current_size = 0;

void* operator new(size_t size)
{
    MemTracker::inc(size);
    return malloc(size);
}
void operator delete(void* ptr)
{
    free(ptr);
}

void FuncOne()
{
    MemTracker(__func__);
    int* i = new int[100];
    delete[] i;
    i = new int[200];
    delete[] i;
    MemTracker::print();
    MemTracker::reset();
}
void FuncTwo()
{
    MemTracker(__func__);
    char* c = new char[1024];
    delete[] c;
    c = new char[2048];
    delete[] c;
    MemTracker::print();
    MemTracker::reset();
}
int main()
{
    FuncOne();
    FuncTwo();
    FuncTwo();
    FuncTwo();
    return 0;
}

打印:

FuncOne allocated: 1200 bytes.
FuncTwo allocated: 3072 bytes.
FuncTwo allocated: 3072 bytes.
FuncTwo allocated: 3072 bytes.

您正在使用什么平台?可能会有特定于平台的解决方案而不更改代码库中的功能。

如果您使用的是Microsoft Visual Studio,则可以使用编译器交换机/GH和/GH,让您可以定义的编译器调用功能_penter_pexit。在这些功能中,您可以查询程序使用的内存数量。那里应该有足够的信息来弄清每个功能中分配了多少内存。

在此MSDN文章中提供了用于检查内存使用的示例代码。