Fix memory leak due to bad index