fix memory leak and insert bug