Technology regression 01-windows Memory allocation tool

Source: Internet
Author: User

A long time did not write technical aspects of things, this half-year is mainly in the study of other people's things, to improve their own relatively large, is a technology to return it, this learning journey is to end the focus of technology, began to apply to find a breakthrough, that is, to complete technical accumulation or for the accumulation of technology to do a solid preparation.

One of the crazy things about C + + is memory management, illegal access, cross-border, wild pointers, leaks, memory allocators, and so on, and sometimes a programmer can be confused. CRT has a number of functions of the stack check to complete the basic memory health checks, MFC also has some simple object checking mechanism, of course, the Java,. NET and other SDK of the super-heavyweight package, even if the occurrence of an object error will be able to tell you the stack information plainly (at least on the surface, I have not developed these two languages specifically. The following is the implementation of a cattle company memory allocation tool, the basic implementation of memory leak check, object legality check, for me is enough.


In order to track memory allocation blocks, the following structure is designed:

//+--------------------------------------------------------------
//
prefix struct body for each request allocation memory block
Used to track all request allocation blocks and request assignment names
//
//---------------------------------------------------------------
struct DBGALLOCHDR
{
dbgallochdr* Pdbgahprev; The previous memory is a size
dbgallochdr* Pdbgahnext; Behind a memory header
DWORD iallocated; Record is the number of times the request assignment operation
DWORD Tid; ID of the request allocation thread
size_t Cbrequest; Request Allocation size
Char szname[64]; Request Allocation block name
DWORD adwguard[4];//Protection Head
};

//+--------------------------------------------------------------
//
Suffix structure for each request allocation memory block
Use a specific data fill to detect that the pointer is legal
//
//---------------------------------------------------------------
struct Dbgallocfoot
{
DWORD Adwguard[4];
};

Root of memory trace block, all allocation blocks can be obtained by root
DBGALLOCHDR G_dbgahroot =
{
&g_dbgahroot,
&g_dbgahroot,
0,
(DWORD)-1
};



In order to implement multi-thread memory allocation tracking, TLS technology is used to save the current assignment information using a threaded local object:

Thread-local object structure, which assists in implementing request memory allocation records for each thread
struct dbgthreadstate
{
Dbgthreadstate* Ptsnext;
Dbgthreadstate* Ptsprev;

ADD Globals below
void* pvrequest; The last time a thread requested a pointer to allocate memory
size_t Cbrequest; The size of the last request that the thread allocated memory
};



Actual allocated memory size during debugging = Request Assignment + allocation header + assigned tail
size_t _actualsizefromrequestsize (size_t CB)
{
Return cb+sizeof (DBGALLOCHDR) +sizeof (dbgallocfoot);
}



The main implementations of the memory-allocation workers have the following:

void* _memalloc (ULONG CB);
void* _memallocclear (ULONG CB);
HRESULT _memrealloc (void** PPV, ULONG CB);
ULONG _memgetsize (void* PV);
void _memfree (void* PV);
HRESULT _memallocstring (LPCTSTR pchsrc, lptstr* ppchdst);
HRESULT _memallocstring (ULONG cch, LPCTSTR pchsrc, lptstr* ppchdst);
HRESULT _memreplacestring (LPCTSTR pchsrc, lptstr* ppchdest);

#define MEMALLOC (CB) _MEMALLOC (CB)
#define MEMALLOCCLEAR (CB) _memallocclear (CB)
#define MEMREALLOC (PPV, CB) _MEMREALLOC (PPV, CB)
#define MEMGETSIZE (PV) _memgetsize (PV)
#define Memfree (PV) _memfree (PV)
#define Memallocstring (PCH, ppch) _memallocstring (PCH, PPCH)
#define Memallocstringbuffer (CCH, PCH, ppch) _memallocstring (CCH, PCH, PPCH)
#define Memreplacestring (PCH, ppch) _memreplacestring (PCH, PPCH)
#define Memfreestring (PCH) _memfree (PCH)



To implement the new delete override of a class through a macro:

#define DECLARE_MEMALLOC_NEW_DELETE () \
Inline void* __cdecl operator new (size_t CB){return (Memalloc (CB));} \
Inline void* __cdecl operator new[] (size_t CB){ return (Memalloc (CB));  } \
     inline void __cdecl operator delete (VOID* PV)    { memfree (PV);  }

#define  declare_memclear_new_delete ()  \
    inline void* __cdecl operator new (SIZE_T CB)     { return (MemAllocClear (CB));  }  \
    inline void* __cdecl operator new[] (SIZE_T CB)   { return (Memallocclear (CB));  } \
    inline void __cdecl operator delete (VOID* PV)     { memfree (PV);  }



You can override the global new delete when you apply it:

Test Global New Delete
void* __cdecl operator new (size_t CB){return (Memalloc (CB));}
void* __cdecl operator new[] (size_t cb) {return (Memalloc (CB));}
void __cdecl operator Delete (void* PV) {memfree (PV);}


Use Note:
The process needs to be called when it starts:
_dbgdllprocessattach ();
_afxglobaldata._hprocessheap = GetProcessHeap ();

The process needs to be called when it exits:
_dbgdllprocessdetach ();

Test Case:

Test base type
void Testbuiltin ()
{
Basic type
int* pInt = new int (10);
int* pintary = new INT[10];
char* pStr = new char[100];
Memsetname ((pStr, "String"));
}

Test class
void TestClass ()
{
cls* pcls = new Cls ();
}

Test release
void Testok ()
{
cls* pcls = new Cls ();
Delete pcls;
Pcls = NULL;
}

DWORD WINAPI ThreadProc (LPVOID lpparameter)
{
int* pintary = new int[100];
return 0;
}

Testing multithreading
void Testmultithread ()
{
HANDLE hhandle = CreateThread (null, 0, threadproc, NULL, 0, NULL);
WaitForSingleObject (Hhandle,-1);
}

int main (int argc, char* argv[])
{
_dbgdllprocessattach ();

_afxglobaldata._hprocessheap = GetProcessHeap ();

Testbuiltin ();
TestClass ();
Testmultithread ();
Testok ();

_dbgdllprocessdetach ();
return 0;
}


Debug Output Window Results:
A + 4-0 = [4]
A + 40-0 = [44]
A + 100-0 = [144]
A + 8-0 = [152]
A + 400-0 = [552]
The thread 0x1d38 has exited with code 0 (0x0).
A + 8-0 = [560]
F + 0-8 = [552]
----------leaked Memory Blocks----------
p=0x00144354 cb=400 #=4 tid:0x1d38
p=0x00144294 cb=8 #=3 tid:0x1878
P=0X001441A4 cb=100 #=2 tid:0x1878 String
P=0x001440ec cb=40 #=1 tid:0x1878
P=0x00142a54 cb=4 #=0 tid:0x1878
Total size 552, peak size 560
----------leaked Memory Blocks End------


Where a means that assignment F means release

The tool I have no symptoms of poisoning, intended to be included in the personal small treasure, I hope you like!

Download.

Http://www.cppblog.com/wlwlxj/archive/2009/06/03/86660.html

Technology regression 01-windows Memory allocation tool

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.