Fix crash and memory leaks