Fix memory error, eliminate memory leak in iteration