fix seg fault and memory leak