fixed memory leak
fixed segfaults and memory leaks