Native memory leaks refer to the leakage of memory allocated at the C/C++ layer (through the NDK or system bottom layer) due to improper release. This document describes high-frequency memory leak scenarios and native memory leak analysis cases to help you quickly locate native memory leak issues in your apps.
Leakage caused by native exceptions
Native memory leak caused by ArkTS references
Main method for checking native memory leaks: Use Native Heap for analysis. Native Heap is suitable for detecting complex leakage patterns (such as improper lifecycle management and excessive caching). It requires analysis based on the call stack and service scenarios.
The following figure shows the overall process of using Native Heap for analysis.

Case Background
Symptom: In this case, the problem scenario is reproduced through repeated operations. It is found that the app Native Heap memory usage keeps increasing in a stepwise manner.
Preliminary judgment: Use the Allocation profiling mode to record the memory usage increase process and observe the Native Heap curve in the memory lane. The curve shows a typical stepwise increase, indicating that native memory leakage occurs.


Analysis process
Step 1: Record leak scenarios using Allocation.
1. Use the Allocation template of DevEco Studio Profiler to analyze the information about heap memory allocation and release, memory mapping, and call stacks. The information includes deallocated memory and memory that has not been deallocated. The procedure is as follows: Start the app process, select the Profiler tool, select the device and app process, select the Allocation template, create a session, and configure recording options.

2. Enable the statistics mode and enable asynchronous stack recording (to facilitate tracing to the service code).

3. Click the button to start recording and reproduce the problem scenario.

Step 2: View the memory allocation stack.

3. Switch to the Call Trees tab page. This tab page displays detailed information about the memory allocation stack.

Step 3: Analyze the memory allocation stack.
Search for the symbol names that have high memory usage and are closely related to the service code in the memory allocation stack information. These symbol names are highlighted in the category. Analyze the related code based on the call stack (double-click to jump to the source code) and locate the cause of the memory not being released. It can be seen that the service code malloc performs caching operations, but the free method deallocate memory is not added.

