Fix crash and memory leak