gpt4 book ai didi

c - 为什么内部 Lua 字符串会这样存储?

转载 作者:太空狗 更新时间:2023-10-29 17:02:39 26 4
gpt4 key购买 nike

我想要一个简单的字符串表来存储一堆常量,我想“嘿!Lua 可以做到这一点,让我使用其中的一些函数吧!”

这主要在lstring.h/lstring.c文件中(我用的是5.2)

我会先展示我好奇的代码。它来自 lobject.h

/*
** Header for string value; string bytes follow the end of this structure
*/
typedef union TString {
L_Umaxalign dummy; /* ensures maximum alignment for strings */
struct {
CommonHeader;
lu_byte reserved;
unsigned int hash;
size_t len; /* number of characters in string */
} tsv;
} TString;


/* get the actual string (array of bytes) from a TString */
#define getstr(ts) cast(const char *, (ts) + 1)

/* get the actual string (array of bytes) from a Lua value */
#define svalue(o) getstr(rawtsvalue(o))

如您所见,数据存储在结构之外。要获取字节流,您需要将 TString 的大小加 1,然后得到 char* 指针。

这不是糟糕的编码吗?它在我的 C 类中被钻入 m 中以形成明确定义的结构。我知道我可能在这里搅局,但你真的失去了那么多速度/空间定义一个结构作为数据头而不是为该数据定义一个指针值吗?

最佳答案

这个想法可能是您将 header 和数据分配到一大块数据中,而不是两个:

TString *str = (TString*)malloc(sizeof(TString) + <length_of_string>);

除了只需调用一次 malloc/free 外,您还可以减少内存碎片并增加内存本地化。

但是回答你的问题,是的,这类黑客攻击通常是一种不好的做法,应该格外小心。如果这样做,您可能希望将它们隐藏在宏/​​内联函数层下。

关于c - 为什么内部 Lua 字符串会这样存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8979999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com