Fix memory management problems