From 1e1185c63eec3401388a2d8e6a04eef222291ef2 Mon Sep 17 00:00:00 2001 From: Michal Lenc Date: Fri, 12 Dec 2025 16:29:15 +0100 Subject: [PATCH] libs/libc/obstack/lib_obstack_free.c: fix object check within chunk MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The original condition incorrectly used &h->chunk instead of h->chunk in the calculation whether the object is in the chunk. This could lead to the wrong behavior as the first branch gave incorrect result and thus sometimes the entire obstack was freed even though object was not NULL. The commit also simplifies the logic, we can use pointer arithmetic here and just do h->chunk + 1 as it gives the same result as (FAR char *)h->chunk + sizeof(struct _obstack_chunk). This saves unnecessary cast and sizeof. The second branch should be less than or equal, not just less than. This ensures the object is correctly located in the chunk even after previous obstack_finish was called. Signed-off-by: Michal Lenc Co-authored-by: Karel Kočí --- libs/libc/obstack/lib_obstack_free.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/libs/libc/obstack/lib_obstack_free.c b/libs/libc/obstack/lib_obstack_free.c index 751d471c75c..229bb3f1e96 100644 --- a/libs/libc/obstack/lib_obstack_free.c +++ b/libs/libc/obstack/lib_obstack_free.c @@ -53,9 +53,13 @@ void obstack_free(FAR struct obstack *h, FAR void *object) while (h->chunk) { - if (object >= - (FAR void *)((FAR char *)&h->chunk + sizeof(struct _obstack_chunk)) - && object < (FAR void *)h->chunk->limit) + /* Object has to be after chunk + chunk' header. We can use pointer + * arithmetic here as h->chunk + 1 is the same as + * (FAR char *)h->chunk + sizeof(struct _obstack_chunk) + */ + + if (object >= (FAR void *)(h->chunk + 1) + && object <= (FAR void *)h->chunk->limit) { /* The object is in this chunk so just move object base. * Note: this keeps the last chunk allocated. This is desirable