Made the code check for errors in the memory clean up