CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: How to avoid memory fragments?

  1. #1
    Join Date
    Nov 2010
    Posts
    54

    How to avoid memory fragments?

    I am developing a Visual C++ application. There is an object called CMyObject, as follows:

    typedef CMap<UINT, UINT, void *, void*> CMyMap;

    class CMyObject
    {
    public:
    CMyMap *m_pMyMap;
    …Some other member variables…
    }

    Some instances of CMyObject contains a map, some not. Therefore, to save memory, I define a pointer m_pMyMap and create a new CMap object only if the instance contains a map.

    When I test my app, with the increase of the CMyObject instance, the number of memory blocks allocated and deallocated is also increasing. There are a lot of fragments during this period. To prevent this, I try to override the new/delete operator for CMyObject and CMyMap. But still find many fragments. So I try to trace into the MFC source codes for CMap. I find CMap is just using an internal buffer to store the hash table(m_pHashTable), as follows:

    m_pHashTable = new CAssoc* [nHashSize];

    And for each hash entry, it uses:

    P = (CPlex *)new BYTE[sizeof(CPlex) + nMax *cbElement];

    to allocate the spaces.

    I believe these two may be the reason of the memory fragments and want to eliminate them. However, is there a way to override the new/delete operator for codes such as:

    new CAssoc* [nHashSize]

    and

    (CPlex *)new BYTE[sizeof(CPlex) + nMax *cbElement]

    so that the spaces will be allocated from my own memory manager instead of from the default heap?

  2. #2
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: How to avoid memory fragments?

    CMap already has code in place to manage allocations, that's why you see the allocations going via the CPlex 'dummy' class. There is an overloaded new/delete for CPlex that pools individual allocations into larger 'pages'.
    So no, you can't override that already overriden behaviour.

    MFC's CMap is a dynamic hashmap and as a result it allocates chunks to accomodate growing needs.
    If you need a static hashmap, you'll need to either create your own or find something more suited to your needs, maybe one of the C++ standard library classes.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)