fix memory leaks
bug-free version