fix use after free and memory leak