diff --git a/os/_posix.vp b/os/_posix.vp index 268130d..af1ef06 100644 --- a/os/_posix.vp +++ b/os/_posix.vp @@ -19,11 +19,18 @@ _mbuddy: memhub.MemBuddy* def _stat(path: str) -> posix.Stat*: """Call stat and return a Stat struct pointer. Return None on failure. Note: the Stat struct is allocated via _mbuddy; the caller must free it.""" - st: posix.Stat = posix.Stat() - result: INT = posix.stat(path, &st) - if result != 0: + if _mbuddy is None: return None - return &st + # 不能在栈上构造后返回其地址:栈对象随本帧失效(栈地址逃逸)。 + # 按本函数契约改为 _mbuddy 堆分配,由调用方 free。 + st: posix.Stat* = _mbuddy.alloc(posix.Stat.__sizeof__()) + if st is None: + return None + result: INT = posix.stat(path, st) + if result != 0: + _mbuddy.free(st) + return None + return st def exists(path: str) -> bool: