瀏覽代碼

Scrub malloc handling

Eric Andersen 22 年之前
父節點
當前提交
351727917b
共有 2 個文件被更改,包括 25 次插入16 次删除
  1. 12 8
      libc/misc/dirent/scandir.c
  2. 13 8
      libc/misc/dirent/scandir64.c

+ 12 - 8
libc/misc/dirent/scandir.c

@@ -30,11 +30,6 @@
 #include <sys/types.h>
 #include "dirstream.h"
 
-/*
- * FIXME: This is a simple hack version which doesn't sort the data, and
- * just passes all unsorted.
- */
-
 int scandir(const char *dir, struct dirent ***namelist,
 			 int (*selector) (const struct dirent *),
 			 int (*compar) (const __ptr_t, const __ptr_t))
@@ -52,7 +47,10 @@ int scandir(const char *dir, struct dirent ***namelist,
     while (NULL != readdir(d))
         count++;
 
-    names = malloc(sizeof (struct dirent *) * count);
+    if (!(names = malloc(sizeof (struct dirent *) * count))) {
+	closedir(d);
+	return -1;
+    }
 
     rewinddir(d);
 
@@ -68,8 +66,14 @@ int scandir(const char *dir, struct dirent ***namelist,
     }
     result = closedir(d);
 
-    if (pos != count)
-        names = realloc(names, sizeof (struct dirent *) * pos);
+    if (pos != count) {
+	struct dirent **tmp;
+	if (!(tmp = realloc(names, sizeof (struct dirent *) * pos))) {
+	    free(names);
+	    return -1;
+	}
+	names = tmp;
+    }
 
     if (compar != NULL) {
 	qsort(names, pos, sizeof (struct dirent *), compar);

+ 13 - 8
libc/misc/dirent/scandir64.c

@@ -36,11 +36,6 @@
 #include "dirstream.h"
 
 
-/*
- * FIXME: This is a simple hack version which doesn't sort the data, and
- * just passes all unsorted.
- */
-
 int scandir64(const char *dir, struct dirent64 ***namelist,
 			 int (*selector) (const struct dirent64 *),
 			 int (*compar) (const __ptr_t, const __ptr_t))
@@ -58,7 +53,10 @@ int scandir64(const char *dir, struct dirent64 ***namelist,
     while (NULL != readdir64(d))
         count++;
 
-    names = malloc(sizeof (struct dirent64 *) * count);
+    if (!(names = malloc(sizeof (struct dirent64 *) * count))) {
+	closedir(d);
+	return -1;
+    }
 
     rewinddir(d);
 
@@ -74,8 +72,15 @@ int scandir64(const char *dir, struct dirent64 ***namelist,
     }
     result = closedir(d);
 
-    if (pos != count)
-        names = realloc(names, sizeof (struct dirent64 *) * pos);
+    if (pos != count) {
+	struct dirent64 **tmp;
+	if (!(tmp = realloc(names, sizeof (struct dirent64 *) * pos))) {
+	    free(names);
+	    return -1;
+	}
+	names = tmp;
+    }
+
 
     if (compar != NULL) {
 	qsort(names, pos, sizeof (struct dirent64 *), compar);