add buffer boundary check