fix memory leaks and logic for determinate the endo of query in some situation