Fix memory leak and NPEs