是否有一个我可以使用的库(我自己的编码不足),它为我提供了关于我 malloc'ed 和 free'ed 的次数以及分配的字节数的统计信息?
1 回答
            2        
        
		
如果您想检测内存泄漏等,Valgrind(另见Wikipedia)是一种选择。
我知道,这是一种非常非常基本的方法,但是否#defines适合您的目的?
例如。将这样的内容放入标题中:
#ifdef COUNT_MALLOCS
static int mallocCounter;
static int mallocBytes;
// Attention! Not safe to single if-blocks without braces!
# define malloc(x)        malloc(x); mallocCounter++; mallocBytes += x
# define free(x)          free(x); mallocCounter++
# define printStat()      printf("Malloc count: %d\nBytes: %d\n", mallocCounter, mallocBytes)
#else
# define malloc(x)
# define free(x)
# define printStat()
#endif /* COUNT_MALLOCS */
既不灵活也不安全,但它应该适用于简单的计数。
编辑:
也许最好定义malloc()一个自定义函数,所以单行 if 块是安全的。
static int mallocCounter;
static int mallocBytes;
// ...
static inline void* counting_malloc(size_t size)
{
    mallocCounter++;
    mallocBytes += size;
    return malloc(size);
}
static inline void couting_free(void* ptr)
{
    mallocCounter--;
    free(ptr);
}
#define malloc(x)      counting_malloc(x)
#define free(x)        counting_free(x)
于 2013-11-14T19:10:58.120   回答