scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | Submodules | README | LICENSE

commit ce493d4762b0e907166910d53ffdd14dabb90cb8
parent 5c36de466db99bd44b3ef29b5b8519db129531a3
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:
Msrc/libc/stdlib/malloc.c | 3+++
Msrc/libc/stdlib/realloc.c | 3++-
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)