fix bug and memory leak