Mobile Development 12 min read

Locating Native Memory Leaks in HarmonyOS Apps: Complete Profiling Workflow

This article details common causes of native memory leaks in HarmonyOS apps and provides a step-by-step workflow using DevEco Profiler's Allocation template to reproduce, identify, analyze, and fix leaks via Native Heap and call stack analysis, illustrated with a real-world case study.

HarmonyOS Developer Technology
HarmonyOS Developer Technology
HarmonyOS Developer Technology
Locating Native Memory Leaks in HarmonyOS Apps: Complete Profiling Workflow

Native Memory Leaks in HarmonyOS App Development

In HarmonyOS application development, native memory leaks refer to memory allocated in the C/C++ layer (via NDK or system low-level APIs) that is not properly released. This article covers high-frequency leak scenarios and analysis cases to help developers quickly locate native memory leaks.

1. Common Root Causes and Analysis Process

1.1 Native Self-Exceptions

Basic object leak: Manual heap allocation with malloc / new without calling free / delete, early returns, or lost pointers prevent memory reclamation.

Circular reference: Multiple shared_ptr or sptr objects hold each other, forming a cycle that prevents reference counts from reaching zero and blocks automatic destruction.

Improper lifecycle management: Native resources acquired via system interfaces (file handles, NativeWindow, camera sessions, codecs) are not released via their corresponding release interfaces, causing kernel or system service resource leaks.

Excessive caching: Caches introduced for performance lack size limits or have flawed eviction policies, leading to unbounded growth and long-term occupation of memory.

Business overload (untimely consumption): Producers continuously generate data while consumers stop due to logic errors, blocking, or insufficient capacity, causing buffer queues to accumulate indefinitely and memory to swell.

Business overload (excessive resource consumption): A single operation requests a huge memory block, or multiple high-consumption resources (high-resolution decoding, model textures) are held simultaneously, exceeding device memory limits.

1.2 ArkTS References Causing Native Leaks

Cross-language leaks: ArkTS objects hold native objects via NAPI, but missing, unimplemented, or unreachable Finalizer prevents the native object from being released during garbage collection.

1.3 Standardized Troubleshooting Flow Using Native Heap

Native Heap analysis suits complex leak patterns (e.g., improper lifecycle management, excessive caching) and requires combining call stacks with business context.

Reproduction and log capture: Use DevEco Profiler's Allocation template in statistical mode to record the leak scenario; repeat the suspected leak operation multiple times.

Identify leak points: Click the Native Heap swim lane; in the details pane's Call Tree tab, select Created & Existing to view call stacks with high memory occupancy.

Analyze call stacks: Prioritize Symbol Name entries with high occupancy that are strongly related to business code (bright colors in Category). Double-click to jump to source code and investigate why memory is not released.

Code review: Combine call stack findings with code logic to pinpoint the root cause.

Fix and verify: Modify code, then repeat steps 1–2 to confirm the memory curve stabilizes.

If business logic is normal, the leak is due to ArkTS references causing native leaks ; refer to ArkTS memory leak analysis. If business logic is faulty, fix the relevant code.

Native Heap analysis overall flow diagram
Native Heap analysis overall flow diagram

2. Case Study: Native Memory Leak Analysis Using Native Heap

2.1 Background

Symptom: Repeated operations reproduce a "staircase-like continuous growth" trend in the application's Native Heap memory usage.

Preliminary judgment: Using Allocation statistical mode to record the memory rise, the Native Heap curve in the Memory swim lane shows a typical "staircase growth," confirming a native memory leak.

Memory curve showing staircase growth
Memory curve showing staircase growth
Allocation recording configuration
Allocation recording configuration

2.2 Analysis Process

Step 1: Record Leak Scenario with Allocation

Based on DevEco Studio Profiler's Allocation template, analyze heap memory allocation/release information, memory mapping, and call stacks (including both freed and unfreed memory). Steps: launch app process, select Profiler tool → choose device and app process → select Allocation template → create Session → configure recording options.

Enable statistical mode and simultaneously enable async stack recording (to trace back to business code).

Click the record button and reproduce the problematic scenario.

Allocation template selection
Allocation template selection
Statistical mode and async stack enabled
Statistical mode and async stack enabled
Recording started
Recording started

Step 2: View Memory Allocation Stack

Select the Native Heap sub-swim lane within All Heap.

In the details area's Statistics tab, choose Created & Existing .

Three view modes:

All Allocations: All allocation information within the selected time range.

Created & Existing: Default; memory allocated after the start point and not released before the end point.

Created & Released: Memory allocated after the start point and already released before the end point.

Switch to the Call Trees tab to see detailed memory allocation stack information.

Statistics tab with Created & Existing selected
Statistics tab with Created & Existing selected
Call Trees tab showing allocation stacks
Call Trees tab showing allocation stacks

Step 3: Analyze Memory Allocation Stack

Prioritize Symbol Name entries with high occupancy that are strongly related to business code (bright colors in Category). Double-click to jump to source code and investigate the cause of unreleased memory. In this case, business code performed caching in malloc but did not add free to release memory.

Category color coding: Bright colors represent developer call stacks; green for ArkTS frames, orange for native frames; gray for system call stacks.

Call stack analysis showing malloc without free
Call stack analysis showing malloc without free

Optimization and Fix

Modify code to add free method to release memory.

Re-run the application and record memory allocation stacks again using Allocation.

Repeat the leak scenario multiple times.

Verification results:

Memory curve shows no significant rise.

Leak issue is fixed.

Verification showing stable memory curve
Verification showing stable memory curve

Summary

This article provides a clear troubleshooting path for common native memory leaks in HarmonyOS app development: deep analysis using Native Heap combined with call stacks, distinguishing between "native self-exceptions" and "ArkTS cross-language references" as two root-cause categories, and leveraging DevEco Profiler's Allocation template to achieve a complete closed loop of reproduction, localization, repair, and verification.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

HarmonyOSMemory ProfilingNative Memory LeakNative HeapDevEco ProfilerAllocation TemplateC/C++ Memory ManagementCall Stack Analysis
HarmonyOS Developer Technology
Written by

HarmonyOS Developer Technology

HarmonyOS developers provide key technology analysis, version updates, Codelabs practice, and event information for HarmonyOS. Welcome developers to join the HarmonyOS ecosystem and create infinite possibilities together!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.