Memory leak and error prevention