Fixed the crash and the memory leaks