关于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要放到后面执行。

相关推荐
玩转C语言和数据结构1 天前
Lua下载和安装教程(附安装包)
lua·lua下载·lua安装教程·lua下载和安装教程·lua安装包
Arva .1 天前
HTTP Client
网络协议·http·lua
爱吃小胖橘2 天前
Lua语法(2)
开发语言·unity·lua
ellis19703 天前
LuaC API知识点汇总
unity·lua
爱吃小胖橘6 天前
Lua语法
开发语言·unity·lua
东方芷兰6 天前
JavaWeb 课堂笔记 —— 20 SpringBootWeb案例 配置文件
java·开发语言·笔记·算法·log4j·intellij-idea·lua
1nullptr7 天前
Lua上值与闭包
开发语言·lua
半夏知半秋8 天前
skynet-socket.lua源码分析
服务器·开发语言·学习·架构·lua
夜猫逐梦11 天前
【lua】luajit 命令行使用指南
开发语言·lua
利来利往11 天前
【奇怪的bug】lua的nil不报错
开发语言·bug·lua