Fixed all the segfault and a memory leak