From 6d763a250090e94b7cca0b971aac54b5c468cc18 Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Wed, 12 Aug 2020 11:13:47 -0300 Subject: 'realloc' can fail when shrinking a block According to ISO C, 'realloc' can fail when shrinking a block. If that happens, 'l_alloc' simply ignores the fail and returns the original block. --- lauxlib.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'lauxlib.c') diff --git a/lauxlib.c b/lauxlib.c index 8bdada50..097c3cf3 100644 --- a/lauxlib.c +++ b/lauxlib.c @@ -1011,8 +1011,13 @@ static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { free(ptr); return NULL; } - else - return realloc(ptr, nsize); + else { /* cannot fail when shrinking a block */ + void *newptr = realloc(ptr, nsize); + if (newptr == NULL && ptr != NULL && nsize <= osize) + return ptr; /* keep the original block */ + else /* no fail or not shrinking */ + return newptr; /* use the new block */ + } } -- cgit v1.2.3-55-g6feb