Fix potential buffer overruns and invalid memory access.