fix segfault and memory leak