Skip to contentSkip to conversation

page_owner_sort.c: Fix potential nullptr dereferencing

PATCH New shouc 1 participant 1 message May 21, 2021

lore
Share & tools
lore

shouc

author
#0 lore raw

PATCH 1/1 page_owner_sort.c: Fix potential nullptr dereferencing

"malloc" may return a null pointer when OOM. This is a patch for catching all the OOM cases that may lead to nullptr dereferencing.

---
 tools/vm/page_owner_sort.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)
tools/vm/page_owner_sort.c +11 -3
index 85eb65ea16d3..894a929d2053 100644
@@ -11,10 +11,7 @@
 
 #include <stdio.h>
 #include <stdlib.h>
-#include <sys/types.h>
 #include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
 #include <string.h>
 
 struct block_list {
@@ -72,6 +69,10 @@ static void add_list(char *buf, int len)
 		exit(1);
 	}
 	list[list_size].txt = malloc(len+1);
+	if (list[list_size].txt == NULL) {
+		printf("Out of memory\n");
+		exit(1);
+	}
 	list[list_size].len = len;
 	list[list_size].num = 1;
 	memcpy(list[list_size].txt, buf, len);
@@ -133,6 +134,11 @@ int main(int argc, char **argv)
 
 	list2 = malloc(sizeof(*list) * list_size);
 
+	if (list2 == NULL) {
+		printf("Out of memory\n");
+		exit(1);
+	}
+
 	printf("culling\n");
 
 	for (i = count = 0; i < list_size; i++) {
@@ -149,5 +155,7 @@ int main(int argc, char **argv)
 	for (i = 0; i < count; i++)
 		fprintf(fout, "%d times:\n%s\n", list2[i].num, list2[i].txt);
 
+	fclose(fin);
+	fclose(fout);
 	return 0;
 }
Signature · 1 line
2.27.0