最近我参与了一个关于微 Controller 的C项目。 我们项目中有很多malloc()或calloc()。 我的问题是是否可以在运行时使用一个数组或另一个动态分配数组来记录分配的内存存在持续时间,即从内存分配到它被释放的时间,以及它被释放的位置。 感谢您的帮助。
最佳答案
要“手动”执行此操作,首先,您需要将所有 malloc、calloc 和 free 实例替换为您自己的函数(例如 _malloc、_calloc 和 _free)。对于生产,这些可以定义为原始函数,因此不会产生任何开销,但对于调试代码,您可以让它们调用您自己的函数:
#ifdef _DEBUG
#define _malloc(s) myMalloc(s,__FILE__, __LINE__)
#define _calloc(b,n) myCalloc (b,n,__FILE__, __LINE__)
#define _free(p) myFree (p, __FILE__, __LINE__)
#else
#define _malloc malloc // If not debugging, just use the default
#define _calloc calloc
#define _free free
#endif
#ifdef _DEBUG // Or whatever your compiler preset is
void *myMalloc (size_t sz, const char *pszFile, unsigned long line)
{
// Save the details in a table with the time
...
return malloc (sz);
}
void myFree (void *ptr, const char *pszFile, unsigned long line)
{
// Process the table, do time calculations etc and then remove it
free (ptr);
}
#endif
这是真正重载 malloc 和 free 的唯一方法。常量 FILE 和 LINE 会告诉您内存分配和释放的位置。注意。如果您打算在 myMalloc 中分配表空间,请使用 malloc,而不是 _malloc,否则您可能会陷入无限循环。
关于c - 记录动态内存分配使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36733113/