Skip to content

Conversation

@yangzhg
Copy link
Contributor

@yangzhg yangzhg commented Dec 4, 2025

What changes were proposed in this pull request?

Refactored Stack::Reserve to calculate the current stack size before calling std::realloc.

Why are the changes needed?

This is a fix for Undefined Behavior.

The previous implementation invoked Size() (which reads buf_) after std::realloc(buf_, ...) had already executed. According to the C++ standard, the lifetime of the pointer passed to realloc ends immediately upon the call. Any subsequent access to buf_ (even just for pointer arithmetic in Size()) is invalid.

Although this issue was recently highlighted by GCC 12's stricter analysis (-Wuse-after-free), it represents a logical flaw that exists in all build environments.

Error context (exposed by GCC 12):

/include/sonic/internal/stack.h:45:56: warning: pointer used after ‘void* realloc(void*, size_t)’ [-Wuse-after-free]
   45 |   sonic_force_inline size_t Size() const { return top_ - buf_; }
      |                                                   ~~~~~^~~~~~

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.
@liuq19 liuq19 merged commit eb4d90e into bytedance:master Dec 26, 2025
10 of 23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants