Fixed memory leak and null exception errors