From 7c6bddbe2a697344f441574d61a74a8034d86109 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 17 Dec 2013 13:03:52 -0800 Subject: [PATCH] unix: fix a possible memory leak in uv_fs_readdir Some scandir implementations allocate the dirent struct even if the directory is empty, so if `scandir` returns 0 there may still be memory that needs to get deallocated. I have altered uv__fs_readdir to go to the "deallocation exit area" when 0 files are found in the directory and continue to return early on a return value of -1. I went to add a test for this functionality, but it appears that one already exists (reading an empty directory), so I imagine that the valgrind builds must only be happening on linux instead of OSX as well? I have confirmed manually that a program without this fix will infinitely leak memory, and with this fix the memory usage stays constant. --- src/unix/fs.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/unix/fs.c b/src/unix/fs.c index 1ce21f004..4cfa6b80e 100644 --- a/src/unix/fs.c +++ b/src/unix/fs.c @@ -202,9 +202,12 @@ static ssize_t uv__fs_readdir(uv_fs_t* req) { int i; int n; + dents = NULL; n = scandir(req->path, &dents, uv__fs_readdir_filter, alphasort); - if (n == -1 || n == 0) + if (n == 0) + goto out; /* osx still needs to deallocate some memory */ + else if (n == -1) return n; len = 0; @@ -232,7 +235,7 @@ static ssize_t uv__fs_readdir(uv_fs_t* req) { out: saved_errno = errno; - { + if (dents != NULL) { for (i = 0; i < n; i++) free(dents[i]); free(dents);