Parser - Segmentation fault when calling yytext

自古美人都是妖i 提交于 2019-12-20 05:47:09

问题


My parser is recognizing the grammar and indicating the correct error line using yylineno. I want to print the symbol wich caused the error.

int yyerror(string s)
{
  extern int yylineno;  // defined and maintained in lex.yy.c
  extern char *yytext;  // defined and maintained in lex.yy.c

  cerr << "error: " << s << " -> " << yytext << " @ line " << yylineno << endl;
  //exit(1);
}

I get this error when I write something not acceptable by the grammar:

error: syntax error -> Segmentation fault

Am I not supposed to used yytext? If not what variable contains the symbol that caused the syntax error?

Thanks


回答1:


Are you using lex or flex? If you're using lex,yytext is a char[], not a char*.

EDIT If you aren't using flex you should be, it is superior in every way and has been from the moment of its appearance nearly 30 years ago. lex was obsoleted on that day.




回答2:


Depending on the version of lex you are using, yytext may be an array or may be a pointer. Since it is defined in a different compilation unit, if it is an array and you declare it as a pointer, you won't see any error messages from the compiler or linker (linker generally don't do type checking). Instead it will treat the first several characters in the array as a pointer and try to dereference it and probably crash.

If you are using flex, you can add a %pointer declaration to the first section of your .l file to ensure that it is a pointer and not an array



来源:https://stackoverflow.com/questions/29500258/parser-segmentation-fault-when-calling-yytext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!