소스 검색

libcompat: Do not preallocate list before the loop in scandir

Let the realloc in the loop take care of it once it's needed, this way
we get rid of an additional point of failure.
Guillem Jover 16 년 전
부모
커밋
5ad592f7ef
1개의 변경된 파일6개의 추가작업 그리고 7개의 파일을 삭제
  1. 6 7
      lib/compat/scandir.c

+ 6 - 7
lib/compat/scandir.c

@@ -57,12 +57,8 @@ scandir(const char *dir, struct dirent ***namelist,
 	if (!d)
 	if (!d)
 		return -1;
 		return -1;
 
 
-	used = 0;
-	avail = 20;
-
-	list = malloc(avail * sizeof(struct dirent *));
-	if (!list)
-		return cleanup(d, list, used);
+	list = NULL;
+	used = avail = 0;
 
 
 	while ((e = readdir(d)) != NULL) {
 	while ((e = readdir(d)) != NULL) {
 		if (filter != NULL && !filter(e))
 		if (filter != NULL && !filter(e))
@@ -71,7 +67,10 @@ scandir(const char *dir, struct dirent ***namelist,
 		if (used >= avail - 1) {
 		if (used >= avail - 1) {
 			struct dirent **newlist;
 			struct dirent **newlist;
 
 
-			avail += avail;
+			if (avail)
+				avail *= 2;
+			else
+				avail = 20;
 			newlist = realloc(list, avail * sizeof(struct dirent *));
 			newlist = realloc(list, avail * sizeof(struct dirent *));
 			if (!newlist)
 			if (!newlist)
 				return cleanup(d, list, used);
 				return cleanup(d, list, used);