fix possible buffer overrun and memory leak

https://android.googlesource.com/platform/frameworks/base/+/4a72b3064cecc85c56b8d75bb4a2d9fedbf76ec8%5E2%5E%21/