fixed memory leak and fixed null pointers