fix bugs in freeing of resources