Fix memory leak by releasing references created internally