setprop libc.debug.malloc = 1 is not working

2019-04-11 10:34发布

问题:

I tried to use setprop libc.debug.malloc = 1 to find out leak. I made an demo program and introduced memory leak in that but the above flag is not able to detect this leak. I tried below commands: adb shell setprop libc.debug.malloc 1 adb shell stop adb shell start

jstring Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv* env,
jobject thiz) {
int *p = malloc(sizeof(int));
p[1] = 100;
return (*env)->NewStringUTF(env, "Hello from JNI !");
}

Any help would be appreciated.

Thanks

回答1:

libc.debug.malloc is not valgrind. It tracks native heap allocations, but doesn't really detect leaks directly. It works best in conjuction with DDMS; see this answer for information about using it for native leak chasing (and maybe this older answer).

(Note you can use valgrind on recent versions of Android, but getting it set up can be an adventure.)

FWIW, different levels of libc.debug.malloc are reasonably good at finding use-after-free and buffer overruns:

/* 1  - For memory leak detections.
 * 5  - For filling allocated / freed memory with patterns defined by
 *      CHK_SENTINEL_VALUE, and CHK_FILL_FREE macros.
 * 10 - For adding pre-, and post- allocation stubs in order to detect
 *      buffer overruns.

For example, if you set libc.debug.malloc = 10 and add a free() call to your example above, you'll likely get a warning message from the library because you set p[1] rather than p[0].