fix(os): _posix._stat 改为 _mbuddy 堆分配,消除返回栈地址的悬垂
_stat 原在栈上构造 posix.Stat 并返回其地址,函数返回后指针悬垂(与其 docstring 声明的 '_mbuddy 分配、调用方 free' 不一致)。改为按契约堆分配,失败时 free。
This commit is contained in:
1 parent
05b2b7162d
commit
e3cdb190dc
1 file changed
+11
-4
+11
-4
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user