fix memory and file descriptor leak