Memory allocation method and debugging mechanism

Source: Internet
Author: User

    1. Memory allocation method and debugging mechanism

      1. M memory allocation

        1. Memory allocation functions

MFCWin32 or C-language memory allocation API, there are four memory allocation APIs available for use.

    The heap allocation function for
    1. Win32

       

      heapcreate is used to create heaps, heapalloc allocates a certain amount of space from the heap, HeapAlloc allocated memory cannot be moved, and heapsize can determine the size of the space allocated from the heap HeapFree is used to free space allocated from the heap; HeapDestroy destroys the created heap.

       

    2. Windows traditional Global or local memory allocation function

       

      win32 to ensure compatibility with Win16.

       

    3. The standard memory allocation function for the C language

       

      P align= "Justify" >malloc,calloc,realloc,free, et.

      These functions eventually map stacks of API functions, so the memory allocated by malloc cannot be moved. The modal versions of these functions are

      malloc_dbg,calloc_dbg,realloc_dbg,free_dbg, and so on.

       

    4. Win32 virtual memory allocation function

       

The virtual memory API is the basis for other APIs. The virtual memory API takes the page as the smallest allocation unit, the X86 page length is 4KB, and the page length can be extracted with the GetSystemInfo function. The virtual memory allocation function includes the following functions:

    • LPVOID VirtualAlloc (LPVOID lpvaddress,

DWORD cbsize,

DWORD Fdwallocationtype,

DWORD fdwprotect);

This function is used to assign a certain range of virtual pages. Parameter 1 specifies the starting address, parameter 2 specifies the length of the allocated memory, parameter 3 specifies the allocation method, the value mem_commint or Mem_reserve, and the parameter 4 specifies the identity of the memory that controls access to this allocation, with a value of page_readonly, Page_ ReadWrite or page_noaccess.

    • LPVOID VirtualAllocEx (HANDLE process,

LPVOID Lpvaddress,

DWORD cbsize,

DWORD Fdwallocationtype,

DWORD fdwprotect);

The function is similar to VirtualAlloc, but allows the process to be specified. Virtaulfree, VirtualProtect, and virtualquery all have corresponding extension functions.

    • BOOL VirtualFree (LPVOID lpvaddress,

DWORD dwsize,

DWORD dwFreeType);

This function is used to reclaim or free allocated virtual memory. Parameter 1 specifies the base address for which you want to reclaim or release the memory, and if it is recycled, the parameter 2 can point to anywhere within the range of virtual addresses, and if it is disposed, parameter 2 must be the address returned by VirtualAlloc, and parameter 3 specifies whether to release or reclaim the memory, with a value of mem_ Decommint or Mem_release.

    • BOOL VirtualProtect (LPVOID lpvaddress,

DWORD cbsize,

DWORD Fdwnewprotect,

Pdword pfdwoldprotect);

This function is used to change the assigned page to a protection page. Parameter 1 specifies the base address of the allocation page, parameter 2 specifies the length of the protection page, parameter 3 specifies the protection properties of the page, values Page_read, Page_write, Page_readwrite, and so on, and parameter 4 is used to return the original protection property.

    • DWORD VirtualQuery (lpcvoid lpaddress,

Pmemory_basic_information lpbuffer,

DWORD dwlength

);

This function is used to query the attributes of a specified page in memory. Parameter 1 points to the virtual address you want to query, and parameter 2 is a pointer to the memory basic information structure, and parameter 3 specifies the length of the query.

    • BOOL VirtualLock (LPVOID lpaddress,dword dwsize);

The function is used to lock the memory, and the locked memory page cannot be swapped to the page file. Parameter 1 specifies the starting address of the memory to lock, and parameter 2 specifies the length of the lock.

    • BOOL Virtualunlock (LPVOID lpaddress,dword dwsize);

Parameter 1 specifies the starting address of the memory to unlock, and parameter 2 specifies the length of memory to be unlocked.

      1. New and delete operators for C + +

MFC defines the new and delete operators for both scopes. For new, in either case, the parameter 1 type must be size_t and return a void type pointer.

    1. New and delete operators in the global scope

      The prototype is as follows:

      void _cdecl:: operator new (size_t nSize);

      void __cdecl operator Delete (void* p);

      Debug Version:

      void* __cdecl operator New (size_t nSize, int nType,

      LPCSTR lpszfilename, int nLine)

    2. New and delete Operators for class definitions

The prototype is as follows:

void* PASCAL classname::operator New (size_t nSize);

void PASCAL classname::operator Delete (void* p);

The operator new operator of a class is a static member function of a class that overrides the global operator new for objects of that class. Global operator new is used to allocate memory for objects of internal type, such as int, and for classes that do not have operator new operators defined.

The new operator is mapped to malloc or malloc_dbg,delete is mapped to free or free_dbg.

      1. debugging means

        MFC applications can use the debug means of the C runtime Library, or you can use the debugging tools provided by MFC. Two kinds of debugging methods are described as follows.

        1. C Run-Library provides and supports debugging features

The following debugging features are provided and supported by the C Runtime Library:

    1. Debug information reporting function

      Used to report warnings and error messages when the debug version of the application runs. Including:

      _CrtDbgReport used to report debug information;

      _CrtSetReportMode set whether warning, error, or assertion information;

      _CrtSetReportFile sets whether to write debug information to a file.

    2. Conditional validation or assertion macros:

      Assertion macros are mainly:

      Assert verifies that a condition is satisfied and does not satisfy the terminating program execution.

      The validation functions are mainly:

      _CrtIsValidHeapPointer verifies that a pointer is in the local heap;

      _CrtIsValidPointer verifies that the specified range of memory can be read or written;

      _CrtIsMemoryBlock verifies that a block of memory is in the local heap.

    3. Memory (heap) Debugging:

Malloc_dbg saves information about memory allocations when allocating memory, such as what files, which rows are allocated memory, and so on. There are a series of functions to provide memory diagnostics:

_ Crtmemcheckpoint save Memory Snapshot in a _crtmemstate structure;

_CrtMemDifference comparison of two _crtmemstate;

_CrtMemDumpStatistics dump output The contents of a _crtmemstate structure;

_CrtMemDumpAllObjectsSince the output of information about all objects allocated in the heap since the last snapshot or program began execution;

_CrtDumpMemoryLeaks detects a memory vulnerability since execution of the program, and outputs all allocated objects if there is a vulnerability.

      1. Debugging tools provided by MFC

Based on the debugging functions provided and supported by the C Runtime Library, MFC has designed some classes, functions and so on to assist debugging.

  1. Trace, ASSERT for MFC

    Assert

    Use the Assert assertion to determine whether the program can continue execution.

    TRACE

    Use the trace macro to display or print debugging information. Trace is implemented through the function Afxtrace. Since the Afxtrace function uses the cdecl calling convention, it is possible to accept a variable number of arguments, just like the printf function. It is defined and implemented as follows:

    void Afx_cdecl Afxtrace (lpctstr lpszformat, ...)

    {

    #ifdef _DEBUG//All afxtrace output are controlled by afxtraceenabled

    if (!afxtraceenabled)

    Return

    #endif

    Handle variable number of parameters

    Va_list args;

    Va_start (args, Lpszformat);

    int nbuf;

    TCHAR szbuffer[512];

    Nbuf = _vstprintf (Szbuffer, Lpszformat, args);

    ASSERT (Nbuf < _countof (szbuffer));

    if ((Afxtraceflags & Tracemultiapp) && (AfxGetApp ()! = NULL))

    AfxDump << AfxGetApp ()->m_pszexename << ":";

    AfxDump << szbuffer;

    Va_end (args);

    }

    #endif//_debug

    In the program source code, you can control whether to display tracking information, display what tracking information. If the global variable afxtraceenabled is true, the trace macro can output; otherwise, no trace information is output. If you specify what message is tracked through Afxtraceflags, the trace information is output, for example, to specify "Multilple application Debug", so that afxtraceflags|=tracemultiapp. Information that can be traced is:

    Enum Afxtraceflags

    {

    Tracemultiapp = 1,//Multi-app debugging

    Traceappmsg = 2,//main message pump trace (includes DDE)

    Tracewinmsg = 4,//Windows message tracing

    Tracecmdrouting = 8,//Windows command Routing Trace

    (Set 4+8 for control notifications)

    Traceole = +,//special OLE callback Trace

    Tracedatabase = +,//Special database trace

    Traceinternet = +//special Internet client Trace

    };

    In this way, the application can specify the value of afxtraceenabled in the desired location to open or close the trace switch, specifying the value of Afxtraceflags to filter the trace information.

    Visual C + + provides a trace tool that can also be used to accomplish these functions.

    In order to display the message information, MFC internally defines an array of type AFX_MAP_MESSAG allmessages, which stores the pair of Windows message and message name mappings. For example:

    Allmessages[1].nmsg = Wm_create,

    allmessages[1].lpszmsg = "Wm_create"

    MFC also uses function _afxtracemsg to display trace messages, it can receive a string and a msg pointer, and then, the string and MSG of the various fields of the information group to synthesize a large string and use afxtrace display.

    A detailed implementation of the allmessages and function _afxtracemsg can be found in AfxTrace.cpp.

  2. MFC Object Content Dump

    Object content dumps are the functionality provided by the CObject class, and all classes derived from it can support this functionality by overriding the virtual function dump. Mentioned in the CObject class.

    Definition of virtual function dump:

    Class Classname:public CObject

    {

    Public

    #ifdef _DEBUG

    virtual void Dump (cdumpcontext& dc) const;

    #endif

    ...

    };

    When using dump, it must be given a parameter of type CDumpContext, which specifies that the object will be responsible for outputting debugging information. To do this, MFC provides a pre-defined global CDumpContext object afxdump that transports debugging information to the debugger's debug window. As you can see from the implementation of the previous Afxtrace, MFC uses the AfxDump output trace information to the Debug window.

    The CDumpContext class does not have a base class, and it provides the ability to output diagnostic information in text form.

    For example:

    cperson* Pmyperson = new CPerson;

    Set some fields of the CPerson object ...

    //...

    Now dump the contents

    #ifdef _DEBUG

    Pmyperson->dump (afxdump);

    #endif

  3. MFC object Validity Detection

Object validation is a feature provided by the CObject class, and all classes derived from it can support this functionality by overriding the virtual function AssertValid. Mentioned in the CObject class.

Definition of virtual function AssertValid:

Class Classname:public CObject

{

Public

#ifdef _DEBUG

virtual void AssertValid () const;

#endif

...

};

Using the ASSERT_VALID macro to determine whether an object is valid, the class of the object must override the AssertValid function. The form is: Assert_valid (pobject).

In addition, MFC provides functions to determine whether an address is valid, such as:

Afxismemoryblock,afxisstring,afxisvalidaddress.

      1. Memory Diagnostics

MFC uses DEBUG_NEW to track the number of source files and rows executed when memory is allocated.

Insert the # define new debug_new into each source file so that the debug version uses _malloc_dbg to allocate memory. MFC AppWizard has done this when creating a framework file.

    1. AfxDoForAllObjects

      MFC provides function afxdoforallobjects to track dynamically allocated memory objects, the function prototype is as follows:

      void AfxDoForAllObjects (void (*PFN) (cobject* pobject,

      void* pContext), void* pContext);

      which

      Parameter 1 is a function pointer that invokes the function represented by the pointer on each object afxdoforallobjects.

      Parameter 2 is passed to the function specified by parameter 1.

      AfxDoForAllObjects can detect all objects derived from the CObject object or CObject class that are assigned using new, except for objects that are assigned in global objects, embedded objects, and stacks.

    2. Memory Vulnerability Detection

Only the memory allocated for the debug version of new.

Completing the memory vulnerability detection requires the following series of steps:

    • Call AfxEnableMemoryTracking (True/false) to turn on/off memory diagnostics. Under debug builds, the default is turned on; turning off memory diagnostics can speed up program execution and reduce diagnostic output.

    • Using the MFC global variable AFXMEMDF to more precisely specify the characteristics of the diagnostic output, the default value is Allocmemdf, which can take the following values or either:

Afxmemdf,delayfreememdf,checkalwaysmemdf

Where: Allocmemdf indicates that memory diagnostic output is possible, delayfreememdf indicates whether free or delete is called at the end of the application, which results in the maximum possible allocation memory of the program Checkalwaysmemdf indicates that the function afxcheckmemory is called for memory detection after each allocation or release of memory (AfxCheckMemory checks all memory allocated through new in the heap (without malloc).

This step is optional and non-mandatory.

    • Create a variable oldmemstate of type cmemstate, call the Cmemstate member function checkpoint get the first memory snapshot.

    • After performing a series of memory allocations or releases, create another cmemstate type variable newmemstate, calling Cmemstate's member function checkpoint to get a new memory snapshot.

    • Create a third cmemstate type variable difmemstate, call Cmemstate's member function difference compare oldmemstate and newmemstate, and save the result in the variable difmemstate. If it is not different, it returns false, otherwise true.

    • If different, the call member function dumpstatistics the output comparison result.

For example:

Declare the variables needed

#ifdef _DEBUG

CMemoryState oldmemstate, Newmemstate, diffmemstate;

Oldmemstate.checkpoint ();

#endif

Do your memory allocations and deallocations ...

CString s = "This is a frame variable";

The next object is a heap object

cperson* p = new CPerson ("Smith", "Alan", "581-0215");

#ifdef _DEBUG

Newmemstate.checkpoint ();

if (Diffmemstate.difference (Oldmemstate, newmemstate))

{

TRACE ("Memory leaked!/n");

Diffmemstate.dumpstatistics ();

or diffmemstate.dumpallobjectssince ();

}

#endif

MFC automates the memory vulnerability detection at the end of the application (debug version) and, if there is a vulnerability, outputs information about the vulnerability.

Previous chapter headings record next chapter

http://blog.csdn.net/kl222/article/details/1499816

Memory allocation method and debugging mechanism

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.