fix memory bug and leaks