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

相关推荐
锐策13 小时前
Lua 核心知识点详解
开发语言·lua
lanhuazui1014 小时前
lua中 string.match返回值
lua
无名客014 小时前
redis分布式锁为什么采用Lua脚本实现。而不是事务
redis·分布式·lua·事务
我发在否2 天前
Lua > OpenResty HelloWorld
lua·openresty
测试界清流2 天前
postman接口功能测试
开发语言·lua
lanhuazui103 天前
lua中table键类型及lua中table的初始化有几种方式
lua
程序猿多布3 天前
Lua和C#比较
c#·lua
我发在否4 天前
Lua > Mac Mini M4安装openresty
macos·lua·openresty
Aiah.4 天前
大彩串口屏-烧录与调试
lua·大彩串口屏·ui显示
程序猿多布4 天前
Lua 面向对象编程
lua