From e116e040f3091eca914a06dcd0bdd9f1aea23add Mon Sep 17 00:00:00 2001 From: Kyle Evans Date: Sat, 4 Nov 2023 21:08:36 -0500 Subject: [PATCH] grep: don't rely on implementation-defined malloc(0) behavior The very few places that rely on malloc/calloc of a zero-size region won't attempt to dereference it, so just return NULL rather than rolling the dice with the underlying malloc implementation. Reported by: brooks, Shawn Webb --- usr.bin/grep/util.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/usr.bin/grep/util.c b/usr.bin/grep/util.c index 1805cc74bfc6..936abc41b3ef 100644 --- a/usr.bin/grep/util.c +++ b/usr.bin/grep/util.c @@ -650,6 +650,8 @@ grep_malloc(size_t size) { void *ptr; + if (size == 0) + return (NULL); if ((ptr = malloc(size)) == NULL) err(2, "malloc"); return (ptr); @@ -663,6 +665,8 @@ grep_calloc(size_t nmemb, size_t size) { void *ptr; + if (nmemb == 0 || size == 0) + return (NULL); if ((ptr = calloc(nmemb, size)) == NULL) err(2, "calloc"); return (ptr);