[PATCH] page_owner_sort.c: Fix potential nullptr dereferencing

From: shouc
Date: Fri May 21 2021 - 11:38:09 EST


"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(-)

diff --git a/tools/vm/page_owner_sort.c b/tools/vm/page_owner_sort.c
index 85eb65ea16d3..894a929d2053 100644
--- a/tools/vm/page_owner_sort.c
+++ b/tools/vm/page_owner_sort.c
@@ -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;
}
--
2.27.0