Home > Articles > Programming > Windows Programming

Advanced .NET Debugging: Managed Heap and Garbage Collection

Mario Hewardt takes a look at the internals of the CLR heap manager and the GC and some common pitfalls that can wreak havoc in your application. He shows how to utilize the debuggers and a set of other tools to illustrate how to get to the bottom of the problems.
This chapter is from the book

This chapter is from the book

Manual memory management is a very common source of errors in applications today. As a matter of fact, several online studies indicate that the most common errors are related to manual memory management. Examples of such problems include

  • Dangling pointers
  • Double free
  • Memory leaks

Automatic memory management serves to remove the tedious and error-prone process of managing memory manually. Even though automatic memory management has gained more attention with the advent of Java and the .NET platform, the concept and implementation have been around for some time. Invented by John McCarthy in 1959 to solve the problems of manual memory management in LISP, other languages have implemented their own automatic memory management schemes as well. The implementation of an automatic memory management component has become almost universally known as a garbage collector (GC). The .NET platform also works on the basis of automatic memory management and implements its own highly performing and reliable GC. Although using a GC makes life a lot simpler for developers and enables them to focus on more of the business logic, having a solid understanding of how the GC operates is key to avoiding a set of problems that can occur when working in a garbage collected environment. In this chapter, we take a look at the internals of the CLR heap manager and the GC and some common pitfalls that can wreak havoc in your application. We utilize the debuggers and a set of other tools to illustrate how we can get to the bottom of the problems.

Windows Memory Architecture Overview

Before we delve into the details of the CLR heap manager and GC, it is useful to review the overall memory architecture of Windows. Figure 5-1 shows a high-level overview of the various pieces commonly involved in a process.

Figure 5-1

Figure 5-1 High-level overview of Windows memory architecture

As you can see from Figure 5-1, processes that run in user mode typically use one or more heap managers. The most common heap managers are the Windows heap manager, which is used extensively in most user mode applications, and the CLR heap manager, which is used exclusively by .NET applications. The Windows heap manager is responsible for satisfying most memory allocation/deallocation requests by allocating memory, in larger chunks known as segments, from the Windows virtual memory manager and maintaining bookkeeping data (such as look aside and free lists) that enable it to efficiently break up the larger chunks into smaller-sized allocations requested by the process. The CLR heap manager takes on similar responsibilities by being the one-stop shop for all memory allocations in a managed process. Similar to the Windows heap manager, it also uses the Windows virtual memory manager to allocate larger chunks of memory, also known as segments, and satisfies any memory allocation/deallocation requests from those segments. They key difference between the two heap managers is how the bookkeeping data is structured to maintain the integrity of the heap. Figure 5-2 shows a high-level overview of the CLR heap manager.

Figure 5-2

Figure 5-2 High-level overview of the CLR heap manager

From Figure 5-2, you can see how the CLR heap manager uses carefully managed larger chunks (segments) to satisfy the memory requests. Also interesting to note from Figure 5-2 is the mode in which the CLR heap manager can operate.

There are two modes of operation: workstation and server. As far as the CLR heap manager is concerned, the primary difference is that rather than having just one heap, there is now one heap per processor, where the size of the heap segments is typically larger than that of the workstation heap (although this is an implementation detail that should not be relied upon). From the GC's perspective, there are other fundamental differences between workstation and server primarily in the area of GC threading models, where the server flavor of the GC has a dedicated thread for all GC activity versus the workstation GC, which runs the GC process on the thread that performed the memory allocation.

Each managed process starts out with two heaps with their own respective segments that are initialized when the CLR is loaded. The first heap is known as the small object heap and has one initial segment of size 16MB on workstations (the server version is bigger). The small object heap is used to hold objects that are less than 85,000 bytes in size. The second heap is known as the large object heap (LOH) and has one initial segment of size 16MB. The LOH is used to hold objects greater than or equal to 85,000 bytes in size. We will see the reason behind dividing the heaps based on object size limits later when we discuss the garbage collector internals. It is important to note that when a segment is created, not all of the memory in that segment is committed; rather, the CLR heap manager reserves the memory space and commits on demand. Whenever a segment is exhausted on the small object heap, the CLR heap manager triggers a GC and expands the heap if space is low. On the large object heap, however, the heap manager creates a new segment that is used to serve up memory. Conversely, as memory is freed by the garbage collector, memory in any given segment can be decommitted as needed, and when a segment is fully decommitted, it might be freed altogether.

As briefly mentioned in Chapter 2, "CLR Fundamentals," each object that resides on the managed heap carries with it some additional metadata. More specifically, each object is prefixed by an additional 8 bytes. Figure 5-3 shows an example of a small object heap segment.

Figure 5-3

Figure 5-3 Example of a small object heap segment

In Figure 5-3, we can see that the first 4 bytes of any object located on the managed heap is the sync block index followed by an additional 4 bytes that indicate the method table pointer.

Allocating Memory

Now that we understand how the CLR heap manager, at a high level, structures the memory available to applications, we can take a look at how allocation requests are satisfied. We already know that the CLR heap manager consists of one or more segments and that memory allocations are allotted from one of the segments and returned to the caller. How is this memory allocation performed? Figure 5-4 illustrates the process that the CLR heap manager goes through when a memory allocation request arrives.

Figure 5-4

Figure 5-4 Memory allocation process in the CLR heap manager

In the most optimal case, when a GC is not needed for the allocation to succeed, an allocation request is satisfied very efficiently. The two primary tasks performed in that scenario are those of simply advancing a pointer and clearing the memory region. The act of advancing the allocation pointer implies that new allocations are simply tacked on after the last allocated object in the segment. When another allocation request is satisfied, the allocation pointer is again advanced, and so forth. Please note that this allocation scheme is quite different than the Windows heap manager in the sense that the Windows heap manager does not guarantee locality of objects on the heap in the same fashion. An allocation request on the Windows heap manager can be satisfied from any given free block anywhere in the segment. The other scenario to consider is what happens when a GC is required due to breaching a memory threshold. In this case, a GC is performed and the allocation attempt is tried again. The last interesting aspect from Figure 5-4 is that of checking to see if the allocated object is finalizable. Although not, strictly speaking, a function of the managed heap, it is important to call out as it is part of the allocation process. If an object is finalizable, a record of it is stored in the GC to properly manage the lifetime of the object. We will discuss finalizable objects in more detail later in the chapter.

Before we move on and discuss the garbage collector internals, let's take a look at a very simple application that performs a memory allocation. The source code behind the application is shown in Listing 5-1.

Listing 5-1. Simple memory allocation

using System;
using System.Text;
using System.Runtime.Remoting;


namespace Advanced.NET.Debugging.Chapter5
{
    class Name
    {
        private string first;
        private string last;


        public string First { get { return first; } }
        public string Last { get { return last; } }


        public Name(string f, string l)
        {
            first = f; last = l;
        }
    }


    class SimpleAlloc
    {
        static void Main(string[] args)

        {
            Name name = null;


            Console.WriteLine("Press any key to allocate memory");
            Console.ReadKey();


            name = new Name("Mario", "Hewardt");


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

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

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

The source code in Listing 5-1 is painfully simple, but the more interesting question is, how do we find that particular memory allocation on the managed heap using the debuggers? Fortunately, the SOS debugger extension has a few handy commands that enable us to gain some insight into the contents of the managed heap. The command we will use in this particular example is the DumpHeap command. By default, the DumpHeap command lists all the objects that are stored on the managed heap together with their associated address, method table, and size. Let's run our 05SimpleAlloc.exe application under the debugger and break execution when the Press any key to allocate memory prompt is shown. When execution breaks into the debugger, run the DumpHeap command. A partial listing of the output of the command is shown in the following:

0:004> !DumpHeap
 Address        MT     Size
790d8620  790fd0f0       12
790d862c  790fd8c4       28
790d8648  790fd8c4       32
790d8668  790fd8c4       32
790d8688  790fd8c4       28
790d86a4  790fd8c4       24
790d86bc  790fd8c4       24
...
...
...
total 2379 objects
Statistics:
      MT    Count    TotalSize Class Name
79119954        1           12 System.Security.Permissions.ReflectionPermission
79119834        1           12 System.Security.Permissions.FileDialogPermission
791032a8        1          128 System.Globalization.NumberFormatInfo
79100e38        3          132 System.Security.FrameSecurityDescriptor
791028f4        2          136 System.Globalization.CultureInfo
791050b8        4          144 System.Security.Util.TokenBasedSet
790fe284        2          144 System.Threading.ThreadAbortException
79102290       13          156 System.Int32
790f97c4        3          156 System.Security.Policy.PolicyLevel
790ff734        9          180 System.RuntimeType
790ffb6c        3          192 System.IO.UnmanagedMemoryStream
7912d7c0       11          200 System.Int32[]
790fd0f0       17          204 System.Object
79119364        8          256 System.Collections.ArrayList+SyncArrayList
79101fe4        6          336 System.Collections.Hashtable
79100a18       10          360 System.Security.PermissionSet
79112d68       18          504
System.Collections.ArrayList+ArrayListEnumeratorSimple
79104368       21          504 System.Collections.ArrayList
7912d9bc        6          864 System.Collections.Hashtable+bucket[]
7912dae8        8         1700 System.Byte[]
7912dd40       14         2296 System.Char[]
7912d8f8       23        17604 System.Object[]
790fd8c4     2100       132680 System.String
Total 2379 objects

The output of the DumpHeap command is divided into two sections. The first section contains the entire list of objects located on the managed heap. The DumpObject command can be used on any of the listed objects to get further information about the object. The second section contains a statistical view of the managed heap activity by grouping related objects and displaying the method table, count, total size, and the object's type name. For example, the item

79100a18       10          360 System.Security.PermissionSet

indicates that the object in question is a PermissionSet with a method descriptor of 0x79100a18 and that there are 10 instances on the managed heap with a total size of 360 bytes. The statistical view can be very useful when trying to understand an excessively large managed heap and which objects may be causing the heap to grow.

The DumpHeap command produces quite a lot of output and it can be difficult to find a particular allocation in the midst of all of the output. Fortunately, the DumpHeap command has a variety of switches that makes life easier. For example, the –type and –mt switches enable you to search the managed heap for a given type name or a method table address. If we run the DumpHeap command with the –type switch looking for the allocation our application makes, we get the following:

0:003> !DumpHeap -type Advanced.NET.Debugging.Chapter5.Name
 Address       MT     Size
total 0 objects
Statistics:
      MT    Count    TotalSize Class Name
Total 0 objects

The output clearly indicates that there are no allocations on the managed heap of the given type. Of course, this makes perfect sense because our sample application has not performed its allocation. Resume execution of the application until you see the Press any key to exit prompt. Again, break execution and run the DumpHeap command again with the –type switch:

0:004> !DumpHeap –type Advanced.NET.Debugging.Chapter5.Name
Address       MT     Size
01ca6c7c 002030cc       16
total 1 objects
Statistics:
      MT    Count    TotalSize Class Name
002030cc        1           16 Advanced.NET.Debugging.Chapter5.Name
Total 1 objects

This time, we can see that we have an instance of our type on the managed heap. The output follows the same structure as the default DumpHeap output by first showing the instance specific data (address, method table, and size) followed by the statistical view, which shows the managed heap only having one instance of our type.

The DumpHeap command has several other useful switches depending on the debugging scenario at hand. Table 5-1 details the switches available.

Table 5-1. DumpHeap Switches

Switch

Description

-stat

Limits output to managed heap statistics

-strings

Limits output to strings stored on the managed heap

-short

Limits output to just the address of the objects on the managed heap

-min

Filters based on the minimum object size specified

-max

Filters based on the maximum object size specified

-thinlock

Outputs objects with associated thinlocks

-startAtLowerBound

Begin walking the heap at a lower bound

-mt

Limit output to the specified method table

-type

Limit output to the specified type name (substring match)

This concludes our high-level discussion of the Windows memory architecture and how the CLR heap manager fits in. We've looked at how the CLR heap manager organizes memory to provide an efficient memory management scheme as well as the process that the CLR heap manager goes through when a memory allocation request arrives at its doorstep. The next big question is how the GC itself functions, its relationship to the CLR heap manager, and how memory is freed after it has been considered discarded.

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