Fix mem leak and unchecked dynamic cast reported by Coverity.