之前分析过在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