From c132e6ff499889c61f6b28a7d88e6521611bd346 Mon Sep 17 00:00:00 2001 From: Andrew Bartlett Date: Thu, 27 Oct 2022 13:21:31 +1300 Subject: [PATCH] lib/base: Avoid compiler warning about use-after-free on Fedora 36 While the local stack pointers could be thought of as "only" numbers that are not invalidated by the memory they point at being freed, any use of the pointer after the free is undefined and so warned about (at best). gcc version 12.2.1 20220819 (Red Hat 12.2.1-1) (GCC) Signed-off-by: Andrew Bartlett --- lib/base/json.c | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/lib/base/json.c b/lib/base/json.c index 23928b3a1..c7ef06588 100644 --- a/lib/base/json.c +++ b/lib/base/json.c @@ -715,7 +715,15 @@ parse_string(struct parse_ctx *ctx) /* Allocate or resize our output buffer if need be */ if (need || p == pend) { - char *tmp = realloc(p0, alloc_len + need + 5 /* slop? */); + char *tmp; + + /* + * Work out how far p is into p0 to re-esablish p after + * the realloc() + */ + size_t p0_to_p_len = (p - p0); + + tmp = realloc(p0, alloc_len + need + 5 /* slop? */); if (tmp == NULL) { ctx->error = heim_error_create_enomem(); @@ -723,7 +731,12 @@ parse_string(struct parse_ctx *ctx) return NULL; } alloc_len += need + 5; - p = tmp + (p - p0); + + /* + * We have two pointers, p and p0, we want to keep them + * pointing into the same memory after the realloc() + */ + p = tmp + p0_to_p_len; p0 = tmp; pend = p0 + alloc_len; @@ -974,8 +987,14 @@ parse_string(struct parse_ctx *ctx) free(p0); return NULL; } - p = tmp + (p - p0); - pend = tmp + 1 + (pend - p0); + /* + * We have three pointers, p, pend (which are the same) + * and p0, we want to keep them pointing into the same + * memory after the realloc() + */ + p = tmp + p0_to_pend_len; + + pend = p + 1; p0 = tmp; } *(p++) = '\0';