Fix possible memory leak and NULL pointer dereference