Fix memory leaks on cast operations