avoid accessing invalid buffer
(cherry picked from commit 0896a25)