Fix possible buffer overrun.

Taken from upstream commit 2db3ea29298bdc347f15fbfab6d5746022f05101.