memory leak fix and inclusion of closedir call