'2009/06'에 해당되는 글 1건

  1. 2009.06.30 Win32에서 메모리 사용/변화량 측정방법 (2)

_CrtSetAllocHook함수를 이용하면 쉽게 측정이 가능하다. 아래와 같이 구현하면 AllocHook이 메모리관련 함수가 호출될때마다 호출된다.

#include <crtdbg.h>

 

#define nNoMansLandSize 4

 

typedef struct _CrtMemBlockHeader

{

        struct _CrtMemBlockHeader * pBlockHeaderNext;

        struct _CrtMemBlockHeader * pBlockHeaderPrev;

        char *                      szFileName;

        int                         nLine;

#ifdef _WIN64

        /* These items are reversed on Win64 to eliminate gaps in the struct

        * and ensure that sizeof(struct)%16 == 0, so 16-byte alignment is

        * maintained in the debug heap.

        */

        int                         nBlockUse;

        size_t                      nDataSize;

#else  /* _WIN64 */

        size_t                      nDataSize;

        int                         nBlockUse;

#endif  /* _WIN64 */

        long                        lRequest;

        unsigned char               gap[nNoMansLandSize];

        /* followed by:

        *  unsigned char           data[nDataSize];

        *  unsigned char           anotherGap[nNoMansLandSize];

        */

} _CrtMemBlockHeader;

 

#define pbData(pblock) ((unsigned char *)((_CrtMemBlockHeader *)pblock + 1))

#define pHdr(pbData) (((_CrtMemBlockHeader *)pbData)-1)

 

FILE* g_hfileLog = NULL;

 

int AllocHook(int nAllocType, void *pvData, size_t nSize, int nBlockUse,

                         long lRequest, const unsigned char * szFileName, int nLine)

{

        static size_t sizeAlloc = 0;

        _CrtMemBlockHeader *pHead;

       

        if ( nBlockUse == _CRT_BLOCK )

               return true;

 

        switch (nAllocType)

        {

        case _HOOK_ALLOC:

               sizeAlloc += nSize;

               fprintf(g_hfileLog, "ALLOC\t%d\n", sizeAlloc);

               break;

        case _HOOK_REALLOC:

               break;

        case _HOOK_FREE:             

               pHead = pHdr(pvData);

               sizeAlloc -= pHead->nDataSize;

               fprintf(g_hfileLog, "FREE\t%d\n", sizeAlloc);

               break;

        }

       

        return true;

}

 

int main(int argc, char** argv)

{

        g_hfileLog = fopen("log.txt", "w+");

        fprintf(g_hfileLog, "Start\n");

 

        _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

        _CrtSetAllocHook(AllocHook);

 

 

        fclose(g_hfileLog);

        return 0;

}
저작자 표시 비영리
신고
Posted by NOP 트랙백 0 : 댓글 2

티스토리 툴바