From 48aea5ad398480a48b7b091483445ce61abb3202 Mon Sep 17 00:00:00 2001 From: Zhengguo Yang Date: Thu, 4 Dec 2025 15:04:54 +0800 Subject: [PATCH] fix(stack): fix use-after-free undefined behavior in Reserve The `Stack::Reserve` method previously accessed `buf_` (via `Size()`) after it had been passed to `std::realloc`. According to the C++ standard, the pointer passed to `realloc` becomes indeterminate after the call. Accessing it subsequently constitutes Undefined Behavior (UB), regardless of whether the memory address changed. This patch fixes the logic by caching the size before reallocation. --- include/sonic/internal/stack.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/include/sonic/internal/stack.h b/include/sonic/internal/stack.h index ad499fb..0682650 100644 --- a/include/sonic/internal/stack.h +++ b/include/sonic/internal/stack.h @@ -55,8 +55,9 @@ class Stack { return; } size_t align_cap = SONIC_ALIGN(new_cap); + size_t old_size = Size(); char* tmp = static_cast(std::realloc(buf_, align_cap)); - top_ = tmp + Size(); + top_ = tmp + old_size; buf_ = tmp; sonic_assert(buf_ != NULL); cap_ = buf_ ? new_cap : 0;