Android 如何定位内存泄漏

1. 非root设备,Android O 及以上设备如何定位内存泄漏问题

ndk的代码如下:

 jstring Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv* env,
		jobject thiz) {
	int fd;
	if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		LOGY("Test", "error");
	}
	else
	{
		LOGY("Test", "sucess!!!");
	}
	close(fd);
	char *buff = (char *)malloc(1024);
	strcpy(buff, "hello malloc buff");

    return (*env)->NewStringUTF(env,
		"Hello from JNI !  Compiled with ABI ");
}

以上代码中有一块buffer未释放,那么如何定位出这块buffer内存未释放呢?步骤如下
1、查找该代码块所属的pid (ps |grep APP)
2、dumpsys meminfo --unreachable APP_PID

 Unreachable memory
  1144 bytes in 8 unreachable allocations
  ABI: 'arm'

  1024 bytes unreachable at cbb24800 
   first 20 bytes of contents:
   cbb24800: 68 65 6c 6c 6f 20 6d 61 6c 6c 6f 63 20 62 75 66 hello malloc buf
   cbb24810: 66 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f...............

  24 bytes unreachable at d9a21690
   contents:
   d9a21690: 63 6f 6d 2e 65 78 61 6d 70 6c 65 2e 68 65 6c 6c com.example.hell
   d9a216a0: 6f 6a 6e 69 00 00 00 00                         ojni....

  24 bytes unreachable at d9a216d8
   contents:
   d9a216d8: 3c 70 72 65 2d 69 6e 69 74 69 61 6c 69 7a 65 64 <pre-initialized
   d9a216e8: 3e 00 c3 12 00 00 00 00                         >.......

  16 bytes unreachable at e73478c0
   contents:
   e73478c0: a6 03 10 00 aa 03 10 00 9c d1 ed df 00 00 00 00 ................

  16 bytes unreachable at e7379210
   contents:
   e7379210: ae 03 10 00 b2 03 10 00 c4 d1 ed df 00 00 00 00 ................

  16 bytes unreachable at e7379220
   contents:
   e7379220: b6 03 10 00 ba 03 10 00 ec d1 ed df 00 00 00 00 ................

  16 bytes unreachable at e7379230
   contents:
   e7379230: be 03 10 00 c2 03 10 00 14 d2 ed df 00 00 00 00 ................

  8 bytes unreachable at e7309140
   contents:
   e7309140: 7a 79 67 6f 74 65 00 00                         zygote..

从上述信息 可以看到未释放的内存信息如下:

   1024 bytes unreachable at cbb24800 
   first 20 bytes of contents:
   cbb24800: 68 65 6c 6c 6f 20 6d 61 6c 6c 6f 63 20 62 75 66 hello malloc buf
   cbb24810: 66 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f...............

从该信息可以看到未释放的内存地址为 cbb24800 ,内存大小为1024 ,该内存里的内容为 “hello malloc buf”,从内存大小和内存内容可以定位出具体未释放的内存位置:char *buff = (char *)malloc(1024);

2.已经root过的Android O 及以上的系统如何使用 malloc debug 定位内存泄漏

adb shell setprop wrap.com.google.android.googlequicksearchbox '"LIBC_DEBUG_MALLOC_OPTIONS=backtrace logwrapper"'
adb shell am force-stop com.google.android.googlequicksearchbox
adb logcat -d | grep "malloc debug"

由于未找到root过的8.0及以上的手机,所以上述方案未验证,该方案的出处:https://android.googlesource.com/platform/bionic/+/master/libc/malloc_debug/README.md

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值