Analysing memory leaks

Sometimes bad design and pitching something on production without prior testing or code reviews embrace quality issues. Memory leak is one of the most common factors in software that increases the memory, where often, restarting or killing the process is the only possible solution.

Memory leak is a type of resource leak in which the application does not manage the memory property and does not deallocate or dispose the objects from heap storage.

In the managed world of .NET, GC (garbage collection) is done automatically by the CLR from time to time and developers don't follow the practice of disposing objects and often rely on the GC to free up memory. However, this is not always a good practice with enterprise-level applications or that involve a lot of Disk I/O, Database, and other related operations.

Memory leaks for managed .NET application is a lot more complex to identify, but there are certain tools that help to diagnose the memory leaks in an application.

When we run the managed .NET application, four types of heaps memory are created to store the objects as follows:

Type of Heap Description
Code heap Stores the actual native code instructions when the JIT is done
Small object heap Stores objects that are less than 85K in size
Large object heap Stores objects that are greater than 85K in size
Process heap Process wise heap starts for 1MB and expands

.NET maintains a complete data structure on Stack, where all the primitive data types are stored and the addresses of the objects stored on heap. This is used by the .NET to determine the program execution. Internally, when a method is called, .NET creates a container that contains all the information related to the method parameters, variables, and lines of code that will be executed for that method. If that method is calling another method, a new container is created and stacked on top of it. On the other hand, when the method completes, the container is removed from the top of the stack and so on.

When the GC runs, it checks for the objects allocated on heap storage but not referenced by any other object of program execution. Other than in the stack, there are more references where GC checks for the objects are Static or Global object references, Object finalization, interop references, and CPU registers. These references are known as GC Roots. Garbage collectors traverse the GC Roots tree and check each of the objects being used and if there are no references freed up from memory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.37.191