fix freeing resources in wrong way