Skip to content
This repository was archived by the owner on May 4, 2018. It is now read-only.

Commit 7c6bddb

Browse files
alexcrichtonindutny
authored andcommitted
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.
1 parent f3d311e commit 7c6bddb

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

src/unix/fs.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,9 +202,12 @@ static ssize_t uv__fs_readdir(uv_fs_t* req) {
202202
int i;
203203
int n;
204204

205+
dents = NULL;
205206
n = scandir(req->path, &dents, uv__fs_readdir_filter, alphasort);
206207

207-
if (n == -1 || n == 0)
208+
if (n == 0)
209+
goto out; /* osx still needs to deallocate some memory */
210+
else if (n == -1)
208211
return n;
209212

210213
len = 0;
@@ -232,7 +235,7 @@ static ssize_t uv__fs_readdir(uv_fs_t* req) {
232235

233236
out:
234237
saved_errno = errno;
235-
{
238+
if (dents != NULL) {
236239
for (i = 0; i < n; i++)
237240
free(dents[i]);
238241
free(dents);

0 commit comments

Comments
 (0)