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?
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.