Updated move function to remove memory leak and iterating out of bounds