From 2c66217af81f16675e611ed6a65bc92efc161bf2 Mon Sep 17 00:00:00 2001 From: Simon Tatham Date: Tue, 21 Jan 2020 20:04:15 +0000 Subject: [PATCH] Fix undefined behaviour in safegrowarray. UBsan points out that if the input pointer is NULL, we'll pass it to memcpy, which is technically illegal by the C standard _even_ if the length you pass with it is zero. (cherry picked from commit 88d5948ead1226a0e364980d93d19fb9f5124f33) --- memory.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/memory.c b/memory.c index 43dd8666..97ae9401 100644 --- a/memory.c +++ b/memory.c @@ -121,9 +121,11 @@ void *safegrowarray(void *ptr, size_t *allocated, size_t eltsize, void *toret; if (secret) { toret = safemalloc(newsize, eltsize, 0); - memcpy(toret, ptr, oldsize * eltsize); - smemclr(ptr, oldsize * eltsize); - sfree(ptr); + if (oldsize) { + memcpy(toret, ptr, oldsize * eltsize); + smemclr(ptr, oldsize * eltsize); + sfree(ptr); + } } else { toret = saferealloc(ptr, newsize, eltsize); }