fix memory leak and some pointers issues