Home > Articles > Programming > Windows Programming

This chapter is from the book

This chapter is from the book

Debugging Managed Heap Fragmentation

Earlier in the chapter, we described a phenomenon known as heap fragmentation, in which free and busy blocks are arranged and interleaved on the managed heap in such a way that they can cause problems in applications that surface as OutOfMemory exceptions; in reality, enough memory is free, just not in a contiguous fashion. The CLR heap manager utilizes a technique known as compacting and coalescing to reduce the risk of heap fragmentation. In this section, we will take a look at an example that can cause heap fragmentation to occur and how we can use the debuggers to identify that a heap fragmentation is in fact occurring and the reasons behind it. The example is shown in Listing 5-8.

Listing 5-8. Heap fragmentation example

using System;
using System.Text;
using System.Runtime.InteropServices;


namespace Advanced.NET.Debugging.Chapter5
{
    class Fragment
    {
        static void Main(string[] args)
        {
            Fragment f = new Fragment();
            f.Run(args);
        }


        public void Run(string[] args)
        {
            if (args.Length < 2)
            {
               Console.WriteLine("05Fragment.exe <alloc. size> <max mem in MB>");
               return;
            }


            int size = Int32.Parse(args[0]);
            int maxmem = Int32.Parse(args[1]);
            byte[][] nonPinned = null;
            byte[][] pinned = null;
            GCHandle[] pinnedHandles = null;


            int numAllocs=maxmem*1000000/size;


            pinnedHandles = new GCHandle[numAllocs];


            pinned = new byte[numAllocs / 2][];
            nonPinned = new byte[numAllocs / 2][];


            for (int i = 0; i < numAllocs / 2; i++)
            {
               nonPinned[i] = new byte[size];
               pinned[i] = new byte[size];
    pinnedHandles[i] =
GCHandle.Alloc(pinned[i], GCHandleType.Pinned);
            }
            Console.WriteLine("Press any key to GC & promo to gen1");
            Console.ReadKey();


            GC.Collect();


            Console.WriteLine("Press any key to GC  & promo to gen2");
            Console.ReadKey();


            GC.Collect();


            Console.WriteLine("Press any key to GC(free non pinned");
            Console.ReadKey();


            for (int i = 0; i < numAllocs / 2; i++)
            {
               nonPinned[i] = null;
            }


            GC.Collect();


            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
}

The source code and binary for Listing 5-8 can be found in the following folders:

  • Source code: C:\ADND\Chapter5\Fragment
  • Binary: C:\ADNDBin\05Fragment.exe

The application enables the user to specify an allocation size and the maximum amount of memory that the application should consume. For example, if we want the allocation size to be 50,000 bytes and the overall memory consumption limit to be 100MB, we would run the application as following:

C:\ADNDBIN\05Fragment 50000 100

The application proceeds to allocate memory, in chunks of the specified allocation size, until the limit is reached. After the allocations have been made, the application performs a couple of garbage collections to promote the surviving objects to generation 2 and then makes the nonpinned objects rootless, followed by another garbage collection that subsequently releases the nonpinned allocations. Let's take a look by running the application under the debugger with an allocation size of 50000 and a max memory threshold of 1GB.

After the Press any key to GC and promo to Gen1 prompt is displayed, the application has finished allocating all the memory and we can take a look at the managed heap using the DumpHeap –stat command:

0:004> !DumpHeap -stat
total 22812 objects
Statistics:
      MT    Count    TotalSize Class Name
79119954        1           12 System.Security.Permissions.ReflectionPermission
79119834        1           12 System.Security.Permissions.FileDialogPermission
791197b0        1           12 System.Security.PolicyManager
...
...
...
791032a8        2          256 System.Globalization.NumberFormatInfo
79101fe4        6          336 System.Collections.Hashtable
7912d9bc        6          864 System.Collections.Hashtable+bucket[]
7912dd40       10          2084 System.Char[]
00395f68      564         13120    Free
7912d8f8       14         17348 System.Object[]
791379e8        1         80012 System.Runtime.InteropServices.GCHandle[]
79141f50        2         80032 System.Byte[][]
790fd8c4     2108        132148 System.String
7912dae8    20002    1000240284 System.Byte[]
Total 22812 objects

The output of the command shows a few interesting fields. Because we are looking specifically for heap fragmentation symptoms, any listed Free blocks should be carefully investigated. In our case, we seem to have 564 free blocks occupying a total size of 13120. Should we be worried about these free blocks causing heap fragmentation? Generally speaking, it is useful to look at the total size of the free blocks in comparison to the overall size of the managed heap. If the size of the free blocks is large in comparison to the overall heap size, heap fragmentation may be an issue and should be investigated further. Another important consideration to be made is that of which generation the possible heap fragmentation is occurring in. In generation 0, fragmentation is typically not a problem because the CLR heap manager can allocate using any free blocks that may be available. In generation 1 and 2 however, the only way for the free blocks to be used is by promoting objects to each respective generation. Because generation 1 is part of the ephemeral segment, which there can only be one of, generation 2 is most commonly the generation of interest when looking at heap fragmentation problems. Let's take a look at what our heap looks like by using the eeheap –gc command:

0:004> !eeheap -gc
Number of GC Heaps: 1
generation 0 starts at 0x56192a54
generation 1 starts at 0x55d91000
generation 2 starts at 0x01c21000
ephemeral segment allocation context: none
 segment    begin allocated     size
003a80e0 790d8620  790f7d8c 0x0001f76c(128876)
01c20000 01c21000  0282db84 0x00c0cb84(12635012)
04800000 04801000  05405ee4 0x00c04ee4(12603108)
05800000 05801000  06405ee4 0x00c04ee4(12603108)
06a50000 06a51000  07655ee4 0x00c04ee4(12603108)
07a50000 07a51000  08655ee4 0x00c04ee4(12603108)
...
...
...
4fd90000 4fd91000  50995ee4 0x00c04ee4(12603108)
50d90000 50d91000  51995ee4 0x00c04ee4(12603108)
51d90000 51d91000  52995ee4 0x00c04ee4(12603108)
52d90000 52d91000  53995ee4 0x00c04ee4(12603108)
53d90000 53d91000  54995ee4 0x00c04ee4(12603108)
54d90000 54d91000  55995ee4 0x00c04ee4(12603108)
55d90000 55d91000  5621afd8 0x00489fd8(4759512)
Large object heap starts at 0x02c21000
 segment    begin allocated     size
02c20000 02c21000  02c23250 0x00002250(8784)
Total Size  0x3ba38e90(1000574608)
––––––––––––––––––––––––––––––
GC Heap Size  0x3ba38e90(1000574608)

The last line of the output tells us that the total GC Heap Size is right around 1GB. You may also notice that there is a rather large list of segments. Because we are allocating a rather large amount of memory, the ephemeral segment gets filled up pretty quickly and new generation 2 segments get created. We can verify this by looking at the starting address of generation 2 in the preceding output (0x01c21000) and correlating the start addresses of each segment in the segment list. Let's get back to the free blocks we saw earlier. In which generations are they located? We can find out by using the dumpheap –type Free command. An abbreviated output follows:

0:004> !DumpHeap -type Free
 Address       MT     Size
01c21000 00395f68        12 Free
01c2100c 00395f68        24 Free
01c24c44 00395f68        12 Free
01c24c50 00395f68        12 Free
01c24c5c 00395f68      6336 Free
01e299d0 00395f68        12 Free
0202a6f4 00395f68        12 Free
0222b418 00395f68        12 Free
0242c13c 00395f68        12 Free
0262ce60 00395f68        12 Free
04801000 00395f68        12 Free
0480100c 00395f68        12 Free
04a01d30 00395f68        12 Free
04c02a54 00395f68        12 Free
04e03778 00395f68        12 Free
0500449c 00395f68        12 Free
052051c0 00395f68        12 Free
05801000 00395f68        12 Free
0580100c 00395f68        12 Free
05a01d30 00395f68        12 Free
05c02a54 00395f68        12 Free
05e03778 00395f68        12 Free
0600449c 00395f68        12 Free
062051c0 00395f68        12 Free
06a51000 00395f68        12 Free
06a5100c 00395f68        12 Free
06c51d30 00395f68        12 Free
06e52a54 00395f68        12 Free
07053778 00395f68        12 Free
0725449c 00395f68        12 Free
074551c0 00395f68        12 Free
07a51000 00395f68        12 Free
07a5100c 00395f68        12 Free
07c51d30 00395f68        12 Free
07e52a54 00395f68        12 Free
08053778 00395f68        12 Free
0825449c 00395f68        12 Free
084551c0 00395f68        12 Free
08a51000 00395f68        12 Free
08a5100c 00395f68        12 Free
08c51d30 00395f68        12 Free
08e52a54 00395f68        12 Free
09053778 00395f68        12 Free
0925449c 00395f68        12 Free
094551c0 00395f68        12 Free
09a51000 00395f68        12 Free
09a5100c 00395f68        12 Free
09c51d30 00395f68        12 Free
09e52a54 00395f68        12 Free
0a053778 00395f68        12 Free
0a25449c 00395f68        12 Free
0a4551c0 00395f68        12 Free
0aee1000 00395f68        12 Free
0aee100c 00395f68        12 Free
0b0e1d30 00395f68        12 Free
0b2e2a54 00395f68        12 Free
0b4e3778 00395f68        12 Free
...
...
...
55192a54 00395f68        12 Free
55393778 00395f68        12 Free
5559449c 00395f68        12 Free
557951c0 00395f68        12 Free
55d91000 00395f68        12 Free
55d9100c 00395f68        12 Free
55f91d30 00395f68        12 Free
56192a54 00395f68        12 Free
02c21000 00395f68        16 Free
02c22010 00395f68        16 Free
02c23020 00395f68        16 Free
02c23240 00395f68        16 Free
total 564 objects
Statistics:
      MT    Count    TotalSize Class Name
00395f68      564        13120      Free
Total 564 objects

By looking at the address of each of the free blocks and correlating the address to the segments from the eeheap command, we can see that a great majority of the free objects reside in generation 2. With a total free size of 13120 in a heap that is right around 1GB in size, the fragmentation now is only a small fraction of one percent. Nothing to worry about (yet). Let's resume the application and keep pressing any key when prompted until you see the Press any key to exit prompt. At that point, break into the debugger and again run the DumpHeap –stat command to get another view of the heap:

0:004> !DumpHeap -stat
total 22233 objects
Statistics:
      MT    Count     TotalSize Class Name
79119954        1            12 System.Security.Permissions.ReflectionPermission
79119834        1            12 System.Security.Permissions.FileDialogPermission
791197b0        1            12 System.Security.PolicyManager
00113038        1            12 Advanced.NET.Debugging.Chapter5.Fragment
791052a8        1            16 System.Security.Permissions.UIPermission
79117480        1            20 System.Security.Permissions.EnvironmentPermission
791037c0        1            20 Microsoft.Win32.SafeHandles.SafeFileMappingHandle
79103764        1            20 Microsoft.Win32.SafeHandles.SafeViewOfFileHandle
...
...
...
7912d8f8       12         17256 System.Object[]
791379e8        1         80012 System.Runtime.InteropServices.GCHandle[]
79141f50        2         80032 System.Byte[][]
790fd8c4     2101        131812 System.String
00395f68    10006      496172124      Free
7912dae8    10002      500120284 System.Byte[]
Total 22233 objects

This time, we can see that the amount of free space has grown considerably. From the output, there are 10006 instances of free blocks occupying a total of 496172124 bytes of memory. To find out how this total amount correlates to our overall heap size, we once again use the eeheap –gc command:

0:004> !eeheap -gc
Number of GC Heaps: 1
generation 0 starts at 0x55d9100c
generation 1 starts at 0x55d91000
generation 2 starts at 0x01c21000
ephemeral segment allocation context: none
 segment    begin allocated     size
003a80e0 790d8620  790f7d8c 0x0001f76c(128876)
01c20000 01c21000  02821828 0x00c00828(12585000)
04800000 04801000  053f9b88 0x00bf8b88(12553096)
...
...
...
54d90000 54d91000  55989b88 0x00bf8b88(12553096)
55d90000 55d91000  562190b0 0x004880b0(4751536)
Large object heap starts at 0x02c21000
 segment    begin allocated     size
02c20000 02c21000  02c23240 0x00002240(8768)
Total Size  0x3b6725f4(996615668)
––––––––––––––––––––––––––––––
GC Heap Size  0x3b6725f4(996615668)

The total GC heap size is reported as 996615668 bytes. Overall, we can say that the heap is approximately 50% fragmented. This can easily be verified by looking at the verbose output of the DumpHeap command:

0:004> !DumpHeap
 Address       MT      Size
...
...
...
55ff381c 7912dae8     50012
55fffb78 00395f68     50012 Free
5600bed4 7912dae8     50012
56018230 00395f68     50012 Free
5602458c 7912dae8     50012
560308e8 00395f68     50012 Free
5603cc44 7912dae8     50012
56048fa0 00395f68     50012 Free
560552fc 7912dae8     50012
56061658 00395f68     50012 Free
5606d9b4 7912dae8     50012
56079d10 00395f68     50012 Free
5608606c 7912dae8     50012
560923c8 00395f68     50012 Free
5609e724 7912dae8     50012
560aaa80 00395f68     50012 Free
560b6ddc 7912dae8     50012
560c3138 00395f68     50012 Free
560cf494 7912dae8     50012
560db7f0 00395f68     50012 Free
560e7b4c 7912dae8     50012
560f3ea8 00395f68     50012 Free
56100204 7912dae8     50012
5610c560 00395f68     50012 Free
...
...
...

From the output, we can see that a pattern has emerged. We have a block of size 50012 that is allocated and in use followed by a free block of the same size that is considered free. We can use the DumpObj command on the allocated object to find out more details:

0:004> !DumpObj 5606d9b4
Name: System.Byte[]
MethodTable: 7912dae8
EEClass: 7912dba0
Size: 50012(0xc35c) bytes
Array: Rank 1, Number of elements 50000, Type Byte
Element Type: System.Byte
Fields:
None

This object is a byte array, which corresponds to the allocations that our application is creating. How did we end up with such an allocation pattern (allocated, free, allocated, free) to begin with? We know that the garbage collector should perform compacting and coalescing to avoid this scenario. One of the situations that can cause the garbage collector not to compact and coalesce is if there are objects on the heap that are pinned (i.e., nonmoveable). To find out if that is indeed the case in our application, we need to see if there are any pinned handles in the process. We can utilize the GCHandles command to get an overview of handle usage in the process:

0:004> !GCHandles
GC Handle Statistics:
Strong Handles: 15
Pinned Handles: 10004
Async Pinned Handles: 0
Ref Count Handles: 0
Weak Long Handles: 0
Weak Short Handles: 1
Other Handles: 0
Statistics:
      MT    Count    TotalSize Class Name
790fd0f0        1           12 System.Object
790feba4        1           28 System.SharedStatics
790fcc48        2           48 System.Reflection.Assembly
790fe17c        1           72 System.ExecutionEngineException
790fe0e0        1           72 System.StackOverflowException
790fe044        1           72 System.OutOfMemoryException
790fed00        1          100 System.AppDomain
790fe704        2          112 System.Threading.Thread
79100a18        4          144 System.Security.PermissionSet
790fe284        2          144 System.Threading.ThreadAbortException
7912d8f8        4         8744 System.Object[]
7912dae8    10000    500120000 System.Byte[]
Total 10020 objects

The output of GCHandles tells us that we have 10004 pinned handles. Further more, in the statistics section, we can see that 10,000 of those handles are used to pin byte arrays. At this point, we are almost there and can do a quick code review that shows that half of the byte array allocations made in the application are explicitly pinned, causing the heap to get fragmented.

Excessive or prolonged pinning is one of the most common reasons behind fragmentation of the managed heap. If pinning is necessary, the developer must ensure that pinning is short lived in order not to interfere too much with the garbage collector.

In the preceding example, we looked at fragmentation as it relates to the managed heap. It is also possible to encounter situations where the virtual memory managed by the Windows virtual memory manager gets fragmented. In those cases, the CLR heap manager may not be able to grow its heap (i.e., allocate new segments) to accommodate allocation requests. The address command can be used to get in-depth information on the systems virtual memory state.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020