Added checks to free memory on errors