Skip to content
ToanLB
Go back

Out of Memory Crashes on Mobile: What Is the True Culprit?

~15 min read
Out of Memory Crashes on Mobile: What Is the True Culprit?

Almost every Unity game development team has experienced this confounding production issue. On development PCs and flagship smartphones like the iPhone 15 Pro or Galaxy S24, the game runs smoothly at 60 FPS. However, when deploying release builds onto entry-level or mid-range devices equipped with 2GB to 3GB of physical RAM, player telemetry reports an alarming pattern: after 10 to 15 minutes of gameplay across two or three level transitions, the application suddenly vanishes, kicking the user straight back to the mobile home screen.

Inspecting Firebase Crashlytics, Sentry, or local engine logs reveals a baffling mystery: there is not a single line of crash logging from C#. No NullReferenceException, no IndexOutOfRangeException, and zero call stack traces exist.

A common reaction among engineers is to assume: “Our C# code is generating too much garbage, overwhelming the Garbage Collector, filling up RAM, and triggering an Out of Memory crash!” Consequently, teams rush to optimize string formatting, strip LINQ calls, rewrite structs, and inject explicit GC.Collect() invocations during level transitions. Yet despite these efforts, subsequent test builds continue crashing on low-end devices without warning.

Why do mobile games terminate silently without trace? If the C# Garbage Collector is rarely the main culprit, where does the real source of Out of Memory (OOM) crashes lie?


The Mechanics of Mobile OOM Crashes: Jetsam and LowMemoryKiller

To understand why C# crash logs remain empty during an OOM event, we must examine how modern mobile operating systems manage scarce physical memory.

Unlike desktop systems that lean on virtual memory swap files spanning tens of gigabytes across storage drives, mobile operating systems (iOS and Android) strictly avoid swapping dirty memory pages to flash storage. Continuous write operations to flash wear out NAND storage chips rapidly and trigger severe frame stuttering. Therefore, when physical RAM falls below critical thresholds, the operating system kernel is left with only one viable action: terminating memory-heavy processes immediately.

flowchart LR
    subgraph APP["1. Unity Game Process"]
        direction TB
        A1["Managed Heap C# (50MB)"]
        A2["Native Engine C++ (850MB)"]
        A1 --- A2
    end

    subgraph OS["2. OS Monitoring Daemons"]
        direction TB
        O1["iOS: Jetsam Daemon"]
        O2["Android: LowMemoryKiller (LMK)"]
        O1 --- O2
    end

    subgraph ACTION["3. Kernel Termination Action"]
        direction TB
        K1["Sends SIGKILL Signal (Signal 9)"]
        K2["Instant Process Annihilation"]
        K3["No Time to Write C# Crash Logs"]
        K1 --> K2 --> K3
    end

    A2 -->|"Dirty Memory Exceeds Ceiling"| OS
    OS -->|"Triggers Process Kill"| K1

On Android: LowMemoryKiller and the lmkd Daemon

Android prioritizes active and background processes using scoring mechanisms known as oom_adj or oom_score_adj. On modern Android versions (Android 9/10+), the kernel collaborates with a userspace daemon named lmkd (Low Memory Killer Daemon), tracking system memory pressure continuously via PSI (Pressure Stall Information). When available physical RAM dips beneath predefined safety thresholds, lmkd scans active applications. Any process holding substantial Dirty Memory with low priority receives an uncatchable SIGKILL (Signal 9).

On iOS: Jetsam Daemon

Apple enforces even stricter memory governance. On iOS, a dedicated system daemon named Jetsam assigns a hard memory limit to each hardware device class. For instance, on a device with 3GB of physical RAM, Jetsam might enforce a strict per-process ceiling of around 1.2GB to 1.4GB of Dirty Memory. When an application approaches this boundary, Jetsam transmits a memory warning. If dirty memory fails to subside immediately, Jetsam terminates the process with an EXC_CRASH (SIGKILL) carrying the reason per-process-limit.

Why Can’t C# Capture These Crashes?

A SIGKILL signal is an uninterceptable operating system kernel directive. It is not an unhandled software exception originating from the Mono or IL2CPP virtual machine. When the kernel dispatches SIGKILL, the game’s entire virtual address space and active execution threads are eradicated instantly.

Consequently:


Dissecting Unity’s 3-Tier Memory Architecture

When diagnosing memory bottlenecks, conflating all process memory into a single bucket is a fatal mistake. Unity applications operate across three distinct memory tiers, each governed by fundamentally different rules:

flowchart LR
    subgraph TIER1["Tier 1: Managed Heap (C#)"]
        direction TB
        M1["Classes, Strings, Lists, Boxed Structs"]
        M2["Collected Automatically by Boehm GC"]
        M3["Footprint: 50MB - 150MB"]
        M1 --> M2 --> M3
    end

    subgraph TIER2["Tier 2: C# Unmanaged (NativeArray)"]
        direction TB
        U1["Unity.Collections in Job System"]
        U2["Allocated via Native Allocators"]
        U3["Manual Dispose() Required"]
        U1 --> U2 --> U3
    end

    subgraph TIER3["Tier 3: Native Engine (C++)"]
        direction TB
        N1["Textures, Meshes, Audio, Shaders"]
        N2["Managed Directly by C++ Engine"]
        N3["Footprint: 75% - 90% of Total RAM"]
        N1 --> N2 --> N3
    end

    TIER1 -.->|"Causes Frame Drops / Spikes"| TIER2
    TIER2 -.->|"90% Root Cause of OOM Crashes"| TIER3

1. Managed Memory (C# Managed Heap)

Managed memory is orchestrated by the Mono or IL2CPP runtime and governed by the Boehm-Demers-Weiser Garbage Collector. This space holds all high-level C# entities: class instances, strings, List<T> collections, arrays, and boxed structs.

Many developers accuse this tier whenever an app crashes. However, in production mobile games, the Managed Heap typically remains between 50MB and 150MB. If C# code creates abundant transient allocations inside the update loop, the direct symptom is frequent GC sweeps producing severe frame stutter (GC spikes) due to Stop-the-World pauses. It is exceedingly rare for the Managed Heap alone to balloon past 1GB and provoke Jetsam or LMK terminations, unless an enormous static collection is leaking data.

2. C# Unmanaged Memory (Native Collections)

This intermediate tier is frequently overlooked. When building high-performance systems using Unity.Collections for the C# Job System or Burst-compiled routines (NativeArray<T>, NativeSlice<T>, NativeList<T>, NativeHashMap), memory is provisioned through Unity’s native memory allocators (Allocator.Persistent, Allocator.TempJob).

Crucially, this memory bypasses the Garbage Collector entirely. If an engineer allocates a NativeArray with Allocator.Persistent and neglects to invoke its Dispose() method, that memory block becomes a permanent native leak that GC cannot touch.

3. Native Memory (C++ Engine Memory)

The Unity Engine core is built with C++. Consequently, the vast majority of substantial game assets live exclusively in Native Memory:

Native Memory is governed by internal C++ engine allocators, with zero automatic garbage collection. Real-world production telemetry consistently demonstrates that Native Engine Memory accounts for 75% to 90% of total process RAM in mobile games. This is the true arena where 90% of mobile Out of Memory crashes occur.


Exposing the 4 Native Memory Pitfalls Causing Silent Crashes

If Native Memory constitutes the lion’s share of your game’s footprint, what architectural mistakes trigger catastrophic native expansion? Here are the four primary culprits encountered in production games.

Pitfall 1: Uncompressed or Incorrectly Formatted Textures

Textures represent the largest single consumer of memory in any game. Retaining uncompressed (RGBA 32-bit) texture formats on mobile is an expensive oversight.

Consider the concrete arithmetic:

If an application loads just a handful of uncompressed full-screen UI atlases or splash assets, Native RAM can surge by 400MB to 600MB almost instantaneously.

Pitfall 2: Overlooking the “Read/Write Enabled” Flag

Within the Inspector settings of Textures and Meshes, Unity exposes a toggle named Read/Write Enabled.

When left active:

The practical result is an immediate 2x memory penalty. Unless a mesh or texture requires programmatic CPU deformation during runtime, keeping Read/Write Enabled checked wastes hundreds of megabytes of valuable memory.

Pitfall 3: Audio Clips Configured with “Decompress On Load”

Audio files represent another stealthy contributor to native memory bloat.

A 3-minute background music (BGM) track compressed as an MP3 or OGG Vorbis file might occupy only 3MB on device storage. However, if its Asset Import Settings retain the default Load Type of Decompress On Load:

Loading two background tracks concurrently inflates Native RAM by over 60MB.

Standard Best Practices:

Pitfall 4: Native Asset Leaks and the “Managed Shell” Trap

This represents the most pervasive architectural misconception bridging C# and C++ within Unity.

In C# code, when declaring Texture2D myTexture, that variable on the Managed Heap is merely a lightweight “wrapper” (a Managed Shell) containing an IntPtr pointing to the underlying C++ Native Object.

flowchart LR
    subgraph MANAGED["Managed Heap (C#)"]
        direction TB
        S1["Static Event / Singleton / Delegate"]
        S2["Managed Shell: Texture2D (Few Bytes)"]
        S1 -->|"Implicit Reference"| S2
    end

    subgraph NATIVE["Native Engine Memory (C++)"]
        direction TB
        N1["Native C++ Texture2D Object"]
        N2["Uncompressed Pixel Buffer (50MB)"]
        N1 --- N2
    end

    S2 -->|"IntPtr Handle Retains"| N1

If a C# component registers with a static event and fails to unsubscribe (-=) upon scene unloading, the Managed Shell remains rooted. As long as this C# shell survives, the C++ engine refuses to release the 50MB native asset underneath!

More deceptively, executing myTexture = null; in C# does not free the native C++ texture. The engine only unloads native memory when asset unloading workflows are executed:


Architectural Solutions: Safe Unmanaged Buffers and Asset Lifecycle Discipline

To eliminate Out of Memory crashes, games require a disciplined architecture that:

  1. Guarantees all C# unmanaged memory (NativeArray) adheres strictly to RAII patterns with foolproof disposal semantics.
  2. Coordinates native asset lifecycles, tracking and unloading heavy assets when they are no longer required.

Consider an Action RPG Swarm Survivor project.

During intense enemy waves, the game computes positioning for thousands of projectiles using the C# Job System with NativeArray<Vector3>. Simultaneously, the encounter loads high-resolution boss visual assets. If unmanaged arrays miss their Dispose() calls, or boss textures linger after the wave concludes, leaked native memory accumulates steadily until the OS terminates the game.

Implementing Safe Unmanaged Buffers with RAII

Below is a production-ready C# architecture providing safe lifecycle tracking for unmanaged buffers, paired with a native asset tracking coordinator calculating memory footprint:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

// Struct wrapper providing safe, deterministic lifecycle management for unmanaged memory outside the Managed Heap.
// Note: This struct models unmanaged RAII principles in pure C#.
// In production Unity Job System environments, developers utilize Unity.Collections.NativeArray<T> with built-in AtomicSafetyHandle.
public struct NativeMemoryBuffer<T> : IDisposable where T : unmanaged
{
    private IntPtr _pointer;
    private int _length;
    private bool _isDisposed;

    public bool IsCreated => _pointer != IntPtr.Zero && !_isDisposed;
    public int Length => _length;
    public unsafe int ByteSize => _length * sizeof(T);

    public unsafe T this[int index]
    {
        get
        {
            if (!IsCreated) throw new ObjectDisposedException(nameof(NativeMemoryBuffer<T>));
            if (index < 0 || index >= _length) throw new ArgumentOutOfRangeException(nameof(index));
            return *(T*)((byte*)_pointer.ToPointer() + index * sizeof(T));
        }
        set
        {
            if (!IsCreated) throw new ObjectDisposedException(nameof(NativeMemoryBuffer<T>));
            if (index < 0 || index >= _length) throw new ArgumentOutOfRangeException(nameof(index));
            *(T*)((byte*)_pointer.ToPointer() + index * sizeof(T)) = value;
        }
    }

    public unsafe NativeMemoryBuffer(int length)
    {
        if (length <= 0)
        {
            throw new ArgumentOutOfRangeException(nameof(length), "Unmanaged buffer length must be greater than zero");
        }

        _length = length;
        int totalBytes = length * sizeof(T);
        // Directly allocates unmanaged process memory
        _pointer = Marshal.AllocHGlobal(totalBytes);
        _isDisposed = false;
    }

    public void Dispose()
    {
        if (!_isDisposed && _pointer != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(_pointer);
            _pointer = IntPtr.Zero;
            _isDisposed = true;
        }
    }
}

// Describes native asset metadata and calculates memory consumption
public class NativeAssetDescriptor
{
    public string Name { get; }
    public int Width { get; }
    public int Height { get; }
    public string Format { get; }
    public bool ReadWriteEnabled { get; }
    public bool HasMipmaps { get; }

    public NativeAssetDescriptor(string name, int width, int height, string format, bool readWriteEnabled, bool hasMipmaps)
    {
        Name = name;
        Width = width;
        Height = height;
        Format = format;
        ReadWriteEnabled = readWriteEnabled;
        HasMipmaps = hasMipmaps;
    }

    // Calculates actual Native RAM consumed by this asset
    public long CalculateMemoryUsage()
    {
        double bitsPerPixel = Format == "ASTC_6x6" ? 3.56 : 32.0;
        double rawBytes = (Width * Height * bitsPerPixel) / 8.0;

        // If Mipmaps are enabled, add roughly 33% overhead
        if (HasMipmaps)
        {
            rawBytes *= 1.3333333333333333;
        }

        long totalBytes = (long)Math.Ceiling(rawBytes);

        // If Read/Write Enabled is active, memory is duplicated in both CPU Native RAM and GPU VRAM
        if (ReadWriteEnabled)
        {
            totalBytes *= 2;
        }

        return totalBytes;
    }
}

// Coordinator tracking and releasing Native assets to prevent memory leaks
public class NativeAssetLifecycleTracker
{
    private readonly Dictionary<string, NativeAssetDescriptor> _activeAssets = new();

    public int TrackedAssetCount => _activeAssets.Count;

    public long TotalNativeBytes
    {
        get
        {
            long sum = 0;
            foreach (var asset in _activeAssets.Values)
            {
                sum += asset.CalculateMemoryUsage();
            }
            return sum;
        }
    }

    public void RegisterAsset(NativeAssetDescriptor asset)
    {
        if (asset == null) throw new ArgumentNullException(nameof(asset));
        _activeAssets[asset.Name] = asset;
    }

    public bool UnregisterAsset(string assetName)
    {
        return _activeAssets.Remove(assetName);
    }

    public void UnloadAllUnusedAssets()
    {
        _activeAssets.Clear();
    }
}

Automated Unit Verification with NUnit

To verify the safety of unmanaged memory management and asset tracking accuracy, we test boundary and standard conditions via an NUnit test fixture:

using System;
using NUnit.Framework;

[TestFixture]
public class NativeMemoryManagementTests
{
    private NativeAssetLifecycleTracker _tracker;

    [SetUp]
    public void SetUp()
    {
        _tracker = new NativeAssetLifecycleTracker();
    }

    [Test]
    public void NativeMemoryBuffer_AllocateAndDispose_ManagesLifecycleAccurately()
    {
        // Standard scenario: Allocating unmanaged array of 1000 floats
        var buffer = new NativeMemoryBuffer<float>(1000);
        Assert.IsTrue(buffer.IsCreated);
        Assert.AreEqual(1000, buffer.Length);
        Assert.AreEqual(4000, buffer.ByteSize);

        // Verify unmanaged memory operations via indexer
        buffer[0] = 42.5f;
        Assert.AreEqual(42.5f, buffer[0]);

        // Safely dispose unmanaged memory
        buffer.Dispose();
        Assert.IsFalse(buffer.IsCreated);
    }

    [Test]
    public void NativeMemoryBuffer_DoubleDispose_DoesNotThrowException()
    {
        // Boundary condition: Protection against double-free errors
        var buffer = new NativeMemoryBuffer<int>(64);
        Assert.IsTrue(buffer.IsCreated);

        buffer.Dispose();
        Assert.IsFalse(buffer.IsCreated);

        // Subsequent disposal must remain harmless
        Assert.DoesNotThrow(() => buffer.Dispose());
    }

    [Test]
    public void NativeMemoryBuffer_ZeroOrNegativeLength_ThrowsArgumentOutOfRangeException()
    {
        // Boundary condition: Invalid allocation length
        Assert.Throws<ArgumentOutOfRangeException>(() =>
        {
            var invalidBuffer = new NativeMemoryBuffer<int>(0);
        });

        Assert.Throws<ArgumentOutOfRangeException>(() =>
        {
            var negativeBuffer = new NativeMemoryBuffer<int>(-50);
        });
    }

    [Test]
    public void NativeAssetDescriptor_RGBA32vsASTC6x6_DemonstratesMassiveMemoryReduction()
    {
        // Calculation verification: 2048x2048 texture with Mipmaps
        var uncompressedTexture = new NativeAssetDescriptor("UI_Atlas_RGBA32", 2048, 2048, "RGBA32", false, true);
        var astcTexture = new NativeAssetDescriptor("UI_Atlas_ASTC", 2048, 2048, "ASTC_6x6", false, true);

        long uncompressedBytes = uncompressedTexture.CalculateMemoryUsage();
        long astcBytes = astcTexture.CalculateMemoryUsage();

        // RGBA 32-bit: ~22.3MB
        Assert.GreaterOrEqual(uncompressedBytes, 22_000_000);

        // ASTC 6x6: ~2.49MB (almost 9x reduction)
        Assert.LessOrEqual(astcBytes, 2_600_000);
        Assert.Greater((double)uncompressedBytes / astcBytes, 8.0);
    }

    [Test]
    public void NativeAssetDescriptor_ReadWriteEnabled_DoublesMemoryConsumption()
    {
        // Enabling Read/Write Enabled doubles memory consumption
        var normalTexture = new NativeAssetDescriptor("Character_Mesh_Tex", 1024, 1024, "RGBA32", false, false);
        var readWriteTexture = new NativeAssetDescriptor("Character_Mesh_Tex", 1024, 1024, "RGBA32", true, false);

        long normalBytes = normalTexture.CalculateMemoryUsage();
        long readWriteBytes = readWriteTexture.CalculateMemoryUsage();

        Assert.AreEqual(normalBytes * 2, readWriteBytes);
    }

    [Test]
    public void NativeAssetLifecycleTracker_RegisterAndUnload_MaintainsAccurateTracking()
    {
        var tex1 = new NativeAssetDescriptor("Bg_Menu", 1024, 1024, "RGBA32", false, false);
        var tex2 = new NativeAssetDescriptor("Bg_Game", 1024, 1024, "RGBA32", false, false);

        _tracker.RegisterAsset(tex1);
        _tracker.RegisterAsset(tex2);

        Assert.AreEqual(2, _tracker.TrackedAssetCount);
        Assert.AreEqual(tex1.CalculateMemoryUsage() + tex2.CalculateMemoryUsage(), _tracker.TotalNativeBytes);

        // Unregister single asset
        _tracker.UnregisterAsset("Bg_Menu");
        Assert.AreEqual(1, _tracker.TrackedAssetCount);
        Assert.AreEqual(tex2.CalculateMemoryUsage(), _tracker.TotalNativeBytes);

        // Unload all assets
        _tracker.UnloadAllUnusedAssets();
        Assert.AreEqual(0, _tracker.TrackedAssetCount);
        Assert.AreEqual(0, _tracker.TotalNativeBytes);
    }
}

Architectural Trade-offs Across Resource Optimization Decisions

Memory optimization is an exercise in balancing RAM headroom, visual clarity, and CPU decoding budgets. The table below outlines these production trade-offs:

Technical CriterionMemory-Optimized OptionDefault / High-Memory OptionReal-world Engineering Trade-off
Texture CompressionASTC 6x6 or ASTC 8x8Uncompressed RGBA 32-bitSaves 70% to 85% RAM; slight visual softening on microscopic edge details
Read/Write ToggleRead/Write Enabled DisabledRead/Write Enabled ActiveRecovers 50% asset RAM; disables runtime CPU pixel reading (GetPixels())
Audio Load TypeStreaming for BGM TracksDecompress On Load for BGMSaves 30MB to 50MB RAM per track; small CPU decoding overhead during playback
Unmanaged MemoryNativeMemoryBuffer<T> (RAII)Standard Managed ArraysModels native/unmanaged buffer lifecycle; requires explicit Dispose() discipline

Production Profiling: Workflows to Eradicate OOM Crashes

When your title encounters silent terminations on mobile hardware, follow this 3-step investigative workflow:

flowchart LR
    subgraph STEP1["1. Inspect OS Logs"]
        direction TB
        L1["iOS: Retrieve Jetsam Crash Reports"]
        L2["Android: Filter logcat for 'lowmemorykiller'"]
        L1 --- L2
    end

    subgraph STEP2["2. Profile Native Memory"]
        direction TB
        M1["Capture Snapshot at Peak Load"]
        M2["Inspect Native Memory Category"]
        M3["Rank Texture2D and AudioClips"]
        M1 --> M2 --> M3
    end

    subgraph STEP3["3. Enforce Safeguards"]
        direction TB
        F1["Standardize on ASTC Presets"]
        F2["Disable Read/Write Globally"]
        F3["Switch BGM Tracks to Streaming"]
        F1 --> F2 --> F3
    end

    STEP1 --> STEP2 --> STEP3
  1. Verify Operating System Termination Cause:
    • On iOS: Open Settings > Privacy & Security > Analytics & Improvements > Analytics Data, locate reports prefixed with JetsamEvent-.... Open the log and inspect whether reason: "per-process-limit" appears under your bundle identifier. This confirms a kernel OOM kill.
    • On Android: Connect the device via USB and execute adb logcat | grep -i lowmemorykiller to confirm kernel LMK termination.
  2. Inspect Native Memory in Unity Memory Profiler:
    • Launch the official Unity Memory Profiler package.
    • Capture a memory snapshot immediately prior to the crash trigger.
    • Disregard the CPU Profiler and GC Alloc graphs. Navigate directly to the Native Memory tab, sorted descending by memory size:
      • Review Texture2D allocations: Are uncompressed RGBA32 or ARGB32 textures consuming tens of megabytes?
      • Review AudioClip assets: Are background music tracks holding 30MB to 50MB due to accidental Decompress On Load settings?
  3. Establish Technical Gateways:
    • Configure Editor Import Presets to enforce ASTC compression and disable Read/Write Enabled across all incoming art directories.
    • Implement Addressables to handle asset loading and unloading in strict synchronization with scene lifecycles, ensuring no unreferenced native textures linger between levels.

Practical Takeaways


Share this post:
Lương Bảo Toàn

Luong Bao Toan

I work in HMI Automotive and Game development, sharing knowledge, hands-on experience, and stories I find interesting throughout my journey.

Did this article bring you value?

If this article helped your work, or you simply enjoyed it and want to support me, you can

Buy me a coffee

Related Articles

Comments & Discussions

Powered by Giscus

Get New Posts via Email

Subscribe to stay updated and never miss new posts from me.

* No spam. You can unsubscribe at any time with a single click.