fix null pointer and memory leak issue