views:

260

answers:

2

I created test.l, input to flex, which ends with the main function.

When the main function is implemented as:

int main(void) { yylex(); return 0; }

I have no problem.

I want to trick the parser into believing that the first character is always a semi-colon, so I implemented main as

int main(void) { unput(';'); yylex(); return 0; }

the above leads to a segment fault.

Why does the use of unput lead to a segment fault?

+4  A: 

It is causing a segment fault because yylex() has not yet initialized the input buffers etc. that are needed by unput().

There's probably a better way to design your scanner without needing to trick it into a leading semicolon, but if you must do this then one solution might be to use start conditions. Something like this:

%x SPECIAL
%%
    BEGIN(SPECIAL); /* Go to SPECIAL state when yylex first called */

<SPECIAL>.  { unput(*yytext); unput(';'); BEGIN(INITIAL); }

... rest of rules ...
Van Gale
Thanks that worked. I wanted to run at the beginning just once, I couldn't figure out how, now I do not need to resort to the trick.
Bongali Babu
A: 

The code under is not wrong in meaning !

int main(void) { unput(';'); yylex(); return 0; }

The problem came from flex which declare the unput macro and of course you should have initialized lex before !

But if you put you main outside of .l file, your soft will not segfault !

Laurent