Fix leaks in copy function