何时释放记忆?(When to free memory?)

编程入门 行业动态 更新时间:2024-10-23 16:18:58
何时释放记忆?(When to free memory?)

我正在研究与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.

更多推荐

本文发布于:2023-07-28 18:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1308138.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:记忆   free   memory

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!