I think we need to set `scan = NULL` regardless of whether the close succeeds.  Otherwise, a subsequent `goto err` will try to free the memory twice...