关于lua源代码中的EXTRA_STACK宏

EXTRA_STACK是给栈额外预留的空间:

c 复制代码
/* extra stack space to handle TM calls and some other extras */
#define EXTRA_STACK 5

这样top之上的几个位置就可以先用,后面再增加栈空间:

c 复制代码
static void callTM (lua_State *L, const TValue *f, const TValue *p1,
                    const TValue *p2, const TValue *p3) {
  setobj2s(L, L->top, f);  /* push function */
  setobj2s(L, L->top+1, p1);  /* 1st argument */
  setobj2s(L, L->top+2, p2);  /* 2nd argument */
  setobj2s(L, L->top+3, p3);  /* 3th argument */
  luaD_checkstack(L, 4);
  L->top += 4;
  luaD_call(L, L->top - 4, 0);
}

我看到这里就想,干嘛不提前luaD_checkstack(L, 4);

c 复制代码
static void callTM (lua_State *L, const TValue *f, const TValue *p1,
                    const TValue *p2, const TValue *p3) {
  setobj2s(L, L->top, f); /* push function */
  setobj2s(L, L->top+1, p1); /* 1st argument */
  setobj2s(L, L->top+2, p2); /* 2nd argument */
  setobj2s(L, L->top+3, p3); /* 3th argument */
  luaD_checkstack(L, 4);
  L->top += 4;
  luaD_call(L, L->top - 4, 0);
}

但是用AddressSanitizer工具测试发现,在执行源码自带的trace-globals.lua时,setobj2s(L, L->top+3, p3);会报使用已free内存。

经过查看代码发现,p3可能是栈上的数据,luaD_checkstack中可能会调用luaD_reallocstack导致p3不可用。

所以luaD_checkstack要放到后面执行。

相关推荐
晴夏。4 天前
unlua实现原理
游戏·ue5·ue4·lua·ue·unlua
晴夏。4 天前
c++调用lua的方法
c++·游戏引擎·lua·ue
chxii5 天前
lua中Table 与 Metatable
lua
xingpanvip5 天前
星盘接口开发文档:组合三限盘接口指南
android·开发语言·前端·python·php·lua
chxii6 天前
lua流程控制语句和table(表)数据结构
开发语言·junit·lua
chxii6 天前
lua 基础语法(上)
开发语言·lua
xingpanvip7 天前
星盘接口开发文档:日运语料接口指南
android·开发语言·前端·css·php·lua
xingpanvip7 天前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
咸鱼永不翻身9 天前
Lua脚本事件检查工具
unity·lua·工具
笑虾9 天前
cocos2d-x lua 加载 Cocos Studio 导出的 csb
游戏引擎·lua·cocos2d