fix array bounds issue and memory leak