Fix problems with freeing memory twice