Fix possible memory/fd leak