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

相关推荐
旷世奇才李先生2 天前
Lua 安装使用教程
开发语言·lua
Accpdaiyekun2 天前
C# 操作mongodb 多次查询快还是使用管道查询速度快
mongodb·c#·lua
快下雨了L3 天前
Lua现学现卖
开发语言·lua
WIN赢12 天前
PostMan使用
测试工具·lua·postman
多多*13 天前
计算机网络期末 网络基础概述
运维·服务器·网络·数据库·计算机网络·oracle·lua
13 天前
Lua复习之何为闭包
开发语言·unity·游戏引擎·lua·交互
码上库利南13 天前
详解Redis的LUA脚本、管道 (Pipelining)、事务事务 (Transactions)
数据库·redis·lua
RPGMZ13 天前
RPGMZ 游戏引擎如何与lua进行互相调用 初探
开发语言·javascript·游戏引擎·lua·rpgmz
Hello.Reader14 天前
Lua 事务双写、RedisGears 异步双写、零停机索引迁移与容量预估
开发语言·lua
虾球xz14 天前
CppCon 2017 学习:Howling at the Moon: Lua for C++ Programmers
开发语言·c++·学习·lua