0

割り当てられたバイト数とともに、malloc と free を行った回数に関する統計を提供する (自分でコーディングする以外に) 使用できるライブラリはありますか?

4

1 に答える 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 に答える