A .NET application can consume more memory over time even when its managed heap appears healthy. This situation often confuses developers because the Garbage Collector is working correctly, managed objects are being collected, and the application does not show an obvious memory leak.
The reason may be native memory consumption.
Native memory is memory allocated outside the managed .NET heap. It can be used by operating system resources, unmanaged libraries, database drivers, image-processing libraries, networking components, and application code that directly interacts with unmanaged memory.
For example, an ASP.NET Core application may use a third-party image-processing library to resize uploaded images. The library may allocate memory outside the managed heap. If those allocations are not released correctly, process memory can continue increasing even though the managed heap remains relatively stable.
This article explains how native memory works in .NET, how to distinguish native memory growth from managed memory problems, and how to investigate native allocations using diagnostic tools.
Understanding Native Memory in .NET
.NET applications primarily use managed memory for objects created through normal C# operations.
Consider this example:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
var customer = new Customer
{
Id = 101,
Name = "John"
};
The Customer object and its managed fields are stored on the managed heap. The Garbage Collector tracks their references and can reclaim their memory when they are no longer reachable.
Native memory works differently.
Native memory is allocated outside the managed heap and is generally managed through explicit allocation and release mechanisms.
Common sources of native memory include:
- Unmanaged libraries called through P/Invoke.
- C and C++ libraries integrated with .NET applications.
- Native image and video processing libraries.
- Database drivers and native database engines.
- Operating system handles and buffers.
- Memory allocated using Marshal.AllocHGlobal.
- Memory allocated using NativeMemory.Alloc.
- Native thread stacks and runtime components.
- Memory-mapped files and unmanaged resource buffers.
For example, a C# application can allocate native memory directly:
using System.Runtime.InteropServices;
IntPtr memory = Marshal.AllocHGlobal(1024 * 1024);
This allocates approximately 1 MB of unmanaged memory.
Unlike a normal managed object, this allocation is not automatically reclaimed just because the IntPtr variable goes out of scope.
The application must release the allocation explicitly:
Marshal.FreeHGlobal(memory);
If the application forgets to release native allocations, memory consumption can grow over time.
Managed Memory vs Native Memory
Understanding the difference between managed and native memory is the first step in diagnosing memory problems.
Area | Managed Memory | Native Memory |
|---|
Allocation | Usually through .NET object allocation | Through native allocation APIs or libraries |
Memory management | Managed by the Garbage Collector | Usually requires explicit resource management |
Cleanup | Automatic when objects become unreachable | Depends on the allocation and ownership mechanism |
Monitoring | GC heap counters and managed heap tools | Operating system and native profiling tools |
Common problems | Object retention and excessive allocation | Unreleased allocations and native resource leaks |
Investigation | dotnet-gcdump and dotnet-dump | Native profilers, process maps, and platform-specific tools |
A process uses more memory than just its managed heap.
It also contains native allocations, runtime structures, thread stacks, loaded modules, JIT-generated code, memory mappings, and other operating system resources.
Therefore, a stable managed heap does not necessarily mean that the complete process memory usage is stable.
Recognizing Native Memory Problems
Native memory problems often appear as gradual increases in process memory.
Consider an ASP.NET Core application that processes images uploaded by users.
During normal operation, its memory consumption may look like this:
Measurement | Initial state | After several hours |
|---|
Managed heap | 250 MB | 260 MB |
Process working set | 450 MB | 1.2 GB |
CPU usage | 25% | 28% |
Request volume | Normal | Normal |
These values are illustrative.
The managed heap has increased only slightly, but the process working set has grown significantly.
This difference is a reason to investigate memory outside the managed heap. It is not proof of a native memory leak because working set and managed heap measurements represent different things.
Common symptoms include:
- Process memory increases continuously.
- Managed heap size remains relatively stable.
- Garbage collection does not significantly reduce process memory.
- Memory consumption increases after specific operations.
- The application eventually experiences an out-of-memory condition.
- Container memory usage increases even when managed allocation metrics appear normal.
- Restarting the application temporarily reduces memory consumption.
The important step is to identify which operation causes the increase and determine where the memory is being allocated.
Monitor Process Memory and Managed Heap Separately
Start by collecting basic runtime metrics.
Install dotnet-counters:
dotnet tool install --global dotnet-counters
Find the running application:
dotnet-counters ps
Start monitoring:
dotnet-counters monitor --process-id 12345
Replace 12345 with the actual process ID.
Pay attention to these metrics:
Metric | Purpose |
|---|
dotnet.process.memory.working_set | Physical memory mapped to the process |
dotnet.gc.heap.total_allocated | Cumulative managed heap allocations |
dotnet.gc.last_collection.heap.size | Managed heap size after the latest collection |
dotnet.gc.last_collection.memory.committed_size | Memory committed by the GC at the latest collection |
dotnet.gc.collections | Number of garbage collections |
dotnet.process.cpu.time | CPU time consumed by the process |
Some of these newer metric names are available starting with .NET 9. Older runtimes expose corresponding information through different runtime counters.
The most useful comparison is between process memory and managed heap measurements.
For example, if working set continues increasing while managed heap size remains relatively stable, investigate native allocations, memory mappings, thread stacks, and other process-level memory consumers.
However, do not calculate native memory simply by subtracting managed heap size from working set. The measurements include different categories of memory, and working set also depends on operating system paging behavior.
Investigate Native Memory With Operating System Tools
The .NET diagnostic tools provide useful information about the managed runtime, but native memory investigation often requires operating system tools.
The exact approach depends on the platform where the application runs.
Investigating Memory on Linux
Linux provides process memory information through the /proc filesystem.
For example:
cat /proc/12345/status
Look for fields such as:
VmSize
VmRSS
VmData
VmStk
These fields provide information about virtual memory, resident memory, data segments, and stack memory.
You can also inspect memory mappings:
cat /proc/12345/smaps_rollup
This provides a summary of the process's mapped memory.
For a more detailed view:
pmap -x 12345
These commands help identify whether memory growth is associated with anonymous mappings, shared libraries, file-backed mappings, or other memory regions.
For example, if anonymous resident memory increases over time, investigate native heap allocations and libraries that allocate memory dynamically.
However, process memory maps do not automatically identify which C# method or native library allocated a particular block. You may need a native allocation profiler to identify the allocation source.
Investigating Memory on Windows
For Windows applications, tools such as VMMap and Windows Performance Analyzer can help investigate process memory.
VMMap provides a detailed breakdown of process memory categories, including:
- Private data.
- Heap allocations.
- Thread stacks.
- Image memory.
- Mapped files.
- Other virtual memory regions.
If private memory increases continuously, investigate whether native libraries or unmanaged allocations are responsible.
Visual Studio also provides Memory Usage diagnostics that support managed, native, and mixed-mode memory analysis for supported applications.
These tools are particularly useful when a .NET application integrates with C or C++ components.
Investigating Memory on macOS
For .NET applications running on macOS, Activity Monitor provides a basic view of process memory consumption.
For deeper investigation, platform tools such as vmmap and Instruments can help examine memory regions and allocation behavior.
For example:
vmmap 12345
Replace the process ID with the actual application process ID.
The output can help identify memory regions and their associated categories.
For detailed allocation analysis, use an appropriate Instruments profiling workflow rather than relying only on the process memory displayed by Activity Monitor.
Understand the Role of dotnet-dump
dotnet-dump is useful for investigating managed memory, runtime state, and certain internal runtime structures.
Install it:
dotnet tool install --global dotnet-dump
Collect a process dump:
dotnet-dump collect \
--process-id 12345 \
--type Full \
--output application-memory.dmp
Analyze the dump:
dotnet-dump analyze application-memory.dmp
Inside the diagnostic console, use:
dumpheap -stat
This displays managed heap statistics.
You can also use:
eeheap
This command displays information about memory consumed by internal runtime structures, including garbage collector and loader information.
These commands are useful when investigating whether managed objects or runtime structures contribute to memory growth.
However, dotnet-dump is not a complete native memory profiler. It does not replace platform-specific native debugging tools and cannot provide all native allocation call stacks.
If the managed heap is stable but process memory continues growing, combine managed dump analysis with operating system memory inspection and native allocation profiling.
Use SafeHandle to Manage Native Resources
One common cause of native resource problems is incorrect ownership and cleanup of unmanaged resources.
Consider an application that calls a native library and receives a native handle.
A basic implementation might look like this:
IntPtr handle = NativeLibrary.CreateResource();
// Perform operations using the handle.
NativeLibrary.ReleaseResource(handle);
The problem is that an exception or early return may prevent ReleaseResource from executing.
This can leave the native resource allocated.
A safer approach is to use SafeHandle.
using Microsoft.Win32.SafeHandles;
public sealed class NativeResourceHandle
: SafeHandleZeroOrMinusOneIsInvalid
{
public NativeResourceHandle()
: base(ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
NativeMethods.ReleaseResource(handle);
return true;
}
}
The application can then use the handle through a managed wrapper.
SafeHandle provides a reliable mechanism for managing native handles and helps protect against resource leaks caused by exceptions and interrupted execution.
The actual ReleaseResource implementation must match the native library's API and ownership rules.
Also remember that SafeHandle is intended for native handles. It is not a universal replacement for every native memory allocation API.
Manage Unmanaged Memory With NativeMemory
Modern .NET provides the NativeMemory API for allocating and releasing unmanaged memory.
For example:
using System.Runtime.InteropServices;
unsafe
{
void* memory = NativeMemory.Alloc(1024 * 1024);
try
{
Span<byte> buffer = new Span<byte>(
memory,
1024 * 1024);
buffer[0] = 100;
}
finally
{
NativeMemory.Free(memory);
}
}
This example allocates approximately 1 MB of unmanaged memory and releases it in a finally block.
Because the allocation is unmanaged, the Garbage Collector does not automatically free it.
The finally block ensures that the allocation is released when the operation completes or throws an exception.
For production code, encapsulate unmanaged allocations in a dedicated owner type or SafeHandle-based abstraction when appropriate. This makes ownership clearer and reduces the chance of accidentally freeing memory too early or forgetting to free it.
Understand GC.AddMemoryPressure
Sometimes a managed object owns a significant amount of native memory.
For example, a managed wrapper may represent an image-processing object that allocates several megabytes through a native library.
The Garbage Collector sees the managed wrapper, but it does not automatically know how much unmanaged memory the wrapper owns.
.NET provides GC.AddMemoryPressure and GC.RemoveMemoryPressure to communicate significant unmanaged memory usage to the Garbage Collector.
A simplified example is:
public sealed class NativeBuffer : IDisposable
{
private IntPtr _memory;
private readonly long _size;
public NativeBuffer(long size)
{
_size = size;
_memory = Marshal.AllocHGlobal(
checked((nint)size));
GC.AddMemoryPressure(_size);
}
public void Dispose()
{
if (_memory == IntPtr.Zero)
{
return;
}
Marshal.FreeHGlobal(_memory);
_memory = IntPtr.Zero;
GC.RemoveMemoryPressure(_size);
}
}
The application reports the unmanaged allocation when it is created and removes the reported pressure when the memory is released.
GC.AddMemoryPressure does not allocate, track, or release native memory. It only informs the Garbage Collector that unmanaged memory consumption should be considered when making collection decisions.
Use it only when the managed object actually owns significant unmanaged memory and ensure that the reported amount is accurate and balanced.
For complex resource ownership, a SafeHandle-based implementation is generally preferable.
Investigate Third-Party Native Libraries
Many .NET applications depend on libraries that internally use native components.
Examples include:
- Image-processing libraries.
- Video encoding and decoding libraries.
- PDF generation and document conversion libraries.
- Database engines with native components.
- Compression libraries.
- Machine learning runtimes.
- Cryptography providers.
A memory problem may originate inside one of these dependencies rather than in application code.
Consider an image-processing API:
app.MapPost("/resize-image", async (
IFormFile file,
CancellationToken cancellationToken) =>
{
await using var stream = file.OpenReadStream();
using var image = Image.Load(stream);
image.Mutate(operation =>
operation.Resize(800, 600));
await using var output = new MemoryStream();
await image.SaveAsJpegAsync(
output,
cancellationToken);
return Results.Ok(new
{
Size = output.Length
});
});
The managed application controls the image object through a library API, but the library may use native or unmanaged resources internally.
When investigating memory growth, examine the library's documentation for disposal requirements and resource ownership.
Also check whether the library has known memory issues in the version being used.
Do not assume that every memory increase after an image operation is a leak. Image decoding, resizing, and encoding legitimately require temporary memory.
Compare memory usage after repeated operations and after all related resources have been disposed.
A Practical Investigation Workflow
Consider an ASP.NET Core service that processes documents and gradually reaches its container memory limit.
Use the following workflow.
Step 1: Confirm the Memory Growth
Monitor the application using dotnet-counters.
Compare process working set with managed heap measurements.
If process memory increases while managed heap size remains relatively stable, investigate memory outside the managed heap.
Step 2: Identify the Operation
Review application logs and distributed traces.
Look for operations that execute before memory consumption increases, such as document conversion, image processing, compression, or native database operations.
Step 3: Inspect Process Memory
On Linux, inspect /proc/PID/smaps_rollup and use pmap.
On Windows, use VMMap or Windows Performance Analyzer.
On macOS, use vmmap and Instruments.
Identify which memory categories are growing.
Step 4: Review Native Resource Ownership
Inspect the code and third-party library integrations.
Look for:
- Missing disposal of native resource wrappers.
- Incorrect SafeHandle implementations.
- Unreleased NativeMemory allocations.
- Incorrect Marshal.FreeHGlobal usage.
- Native objects retained by application-level caches.
- Libraries with known resource-management problems.
Step 5: Collect Detailed Diagnostics
If the problem remains unclear, collect a process dump and use native profiling tools appropriate to the operating system.
For intermittent problems, collect memory information before and after the operation that causes the increase.
Step 6: Validate the Fix
Repeat the same workload after implementing the change.
Compare memory growth, request throughput, and process behavior over time.
A successful fix should prevent uncontrolled memory growth without introducing excessive garbage collection or performance degradation.
Common Mistakes During Native Memory Troubleshooting
- Assuming that stable managed heap size means the application has no memory problem.
- Treating process working set as an exact measurement of native heap allocations.
- Using dotnet-dump as a complete native memory profiler.
- Forgetting to release memory allocated through native APIs.
- Assuming that disposing a managed wrapper always releases every resource owned by a third-party library.
- Calling GC.Collect repeatedly to reduce process memory.
- Using GC.AddMemoryPressure without matching it with GC.RemoveMemoryPressure.
- Ignoring thread stacks, memory mappings, and native runtime structures.
- Collecting large production dumps without checking available disk and container memory.
- Making native memory changes without testing under concurrent workloads.
Best Practices for Preventing Native Memory Problems
- Use SafeHandle for native handles whenever appropriate.
- Release unmanaged memory in a reliable cleanup path.
- Prefer IDisposable and deterministic resource ownership.
- Review the documentation of third-party libraries that use native resources.
- Monitor process memory separately from managed heap size.
- Use operating system memory tools when managed diagnostics are insufficient.
- Apply GC.AddMemoryPressure only when its requirements are satisfied.
- Avoid unnecessary copies between managed and unmanaged buffers.
- Test native resource handling under repeated and concurrent operations.
- Secure memory dumps because they may contain sensitive application data.
Summary
Native memory problems can make a .NET application consume increasing amounts of memory even when the managed heap appears stable.
These problems commonly originate from unmanaged allocations, native libraries, operating system resources, memory mappings, and incorrectly managed native handles.
Start by comparing process working set with managed heap metrics using dotnet-counters. If the measurements suggest that memory growth is outside the managed heap, inspect process memory using platform-specific tools such as VMMap, /proc/PID/smaps_rollup, pmap, or vmmap.
Use dotnet-dump to investigate managed objects and runtime structures, but remember that it is not a complete native memory profiler. For deeper investigation, use native allocation profiling and operating system diagnostics.
Most importantly, establish clear ownership of unmanaged resources. Use SafeHandle, IDisposable, and reliable cleanup paths to ensure native allocations are released correctly.
A healthy .NET application requires more than a healthy managed heap. Understanding and monitoring both managed and native memory is essential for building reliable production services.
Join the conversation! Your thoughts help the community grow.