【分享】基于Android Ndk/Jni的内存泄漏检测

本文介绍了如何使用LeakTracer工具在Android NDK和Jni环境中进行内存泄漏检测。通过替换malloc和free,LeakTracer在检测前后比较内存分配和释放情况。详细步骤包括获取LeakTracer源码,将其整合到Android Studio项目,修改CMakeLists.txt文件,以及展示Java和Native代码示例,演示如何启动和停止内存泄漏检测,并解析检测结果。
摘要由CSDN通过智能技术生成

之前分析过在Android Native中分析内存泄漏的方法:Android Native内存泄露检测(针对Android7.0)但是很遗憾这个方法并不适用于Ndk和Jni,因此我们需要为Ndk和Jni寻找一种合适的方法,他就是LeakTracer
这个工具并没有之前libc那么的智能,他需要我们手动的在怀疑的代码段中加入检测代码,原理是将malloc和free函数替换为LeakTracer中带有插桩性质的函数替代,然后在检测前和检测后比较是否内存有成对的申请和释放。适用于C和C++的内存泄漏检测

上代码:
1. LeakTracer源码获取:

https://github.com/zhuyong006/LeakTracer.git

2. 将LeakTracer源码放入Android Studio中cpp的同级目录如下 :

3. 修改CMakeLists.txt文件,如下:

# Sets the minimum version of CMake required to build the native
# library. You should either keep the default value or only pass a
# value of 3.4.0 or lower.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds it for you.
# Gradle automatically packages shared libraries with your APK.

include_directories(
  src/main/cpp/leak_tracer/include/
)


add_library( # Sets the name of the library.
             leak_tracer

             # Sets the library as a shared library.
             STATIC

             # Provides a relative path to your source file(s).
             # Associated headers in the same location as their source
             # file are automatically included.
             src/main/cpp/leak_tracer/src/AllocationHandlers.cpp
             src/main/cpp/leak_tracer/src/MemoryTrace.cpp)

add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             # Associated headers in the same location as their source
             # file are automatically included.
             src/main/cpp/native-lib.cpp )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because system libraries are included in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值