Fix mem leak and crash