Add array index check to avoid potential buffer overflow.