我正在研究与Bison和Flex的词法分析器/解析器组合,并且稍微担心内存泄漏。
语法非常简单,(到目前为止)我已经能够使用以下定义:
#define YYSTYPE char const *在Flex中,当我读取一个字符串时,我为该字符串分配了足够的内存,然后将其复制到yylval 。 据我所知,这是非常标准的做法。
但是,我无法在任何地方找到任何文档告诉我何时应该释放yylval中的内存。
Bison会自动为我处理吗? 我的行动结束时是否必须这样做? 或者我应该什么时候做呢?
I'm working on a lexer / parser combination with Bison and Flex, and am slightly worried about memory leaks.
The grammar is quite a simple one, and (so far) I have been able to get away with the following definition:
#define YYSTYPE char const *In Flex, when I read a string, I allocate enough memory for that string and then copy it into yylval. As far as I know, this is quite standard practice.
However, I can't find any docs anywhere that tell me when I should free the memory in yylval.
Does Bison handle it automatically for me? Do I have to do it at the end of my action? Or when else should I be doing it?
最满意答案
每次评估右侧时,堆栈中的RHS项目(即$1 , $2等)需要被释放或复制到$$ 。
在执行缩减操作之后,堆栈指针按RHS上的符号数递减,并且$$成为最顶层的项,因此堆栈上剩余的任何内容都将丢失或被后续移入堆栈破坏。
此外,您可能最好使用包含令牌文本字符串及其整数标记值的堆栈类型的结构。
Each time a right-hand-side is evaluated, the RHS items on the stack (i.e., $1, $2, etc.) need to be deallocated or copied to $$.
After the reduction action executes, the stack pointer is decremented by the number of symbols on the RHS and $$ becomes the top-most item, so anything left on the stack will be lost or clobbered by subsequent shifts onto the stack.
Also, you might be better off using a structure for the stack type that contains the token text string and its integer token value.
更多推荐
发布评论