commit 40c0dd60db401444abc61b122fb396af9b0c1114
parent f5cc8f6eeb677435da24372f738055728c9acb93
Author: Roberto E. Vargas Caballero <k0ga@shike2.com>
Date: Sun, 21 Nov 2021 18:45:58 +0100
libc: Add overflow check in malloc() and realloc()
Diffstat:
2 files changed, 5 insertions(+), 1 deletion(-)
diff --git a/src/libc/stdlib/malloc.c b/src/libc/stdlib/malloc.c
@@ -136,6 +136,9 @@ malloc(size_t nbytes)
Header *cur, *prev;
size_t nunits;
+ if (nbytes == 0 || nbytes > SIZE_MAX - sizeof(Header)-1)
+ return NULL;
+
/* 1 unit for header plus enough units to fit nbytes */
nunits = (nbytes+sizeof(Header)-1)/sizeof(Header) + 1;
diff --git a/src/libc/stdlib/realloc.c b/src/libc/stdlib/realloc.c
@@ -1,3 +1,4 @@
+#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -10,7 +11,7 @@ realloc(void *ptr, size_t nbytes)
Header *oh, *prev, *next, *new;
size_t nunits, avail, onbytes, n;
- if (nbytes == 0)
+ if (nbytes == 0 || nbytes > SIZE_MAX - sizeof(Header)-1)
return NULL;
if (!ptr)