Fix OOB heap reads

Fix out-of-bounds heap reads detected by LLVM ASAN.