c - ID 的 Flex 模式给出 'Segmentation fault'

标签 c regex

我有一个 C 语言程序,可以将表达式转换为 RPN(逆波兰表示法)。 我需要做的就是用 Flex 替换用 C 编写的词法分析器代码。我已经做了一些工作,但我在模式方面遇到了问题——具体来说是单词或变量 id。是的,这是类练习。

这是我的:

%{
    #include "global.h"
    int lineno = 1;
    int tokenval = NONE;
%}

%option noyywrap

WS             " "
NEW_LINE       "\n"
DIGIT          [0-9]
LETTER         [a-zA-Z] 
NUMBER         {DIGIT}+
ID             {LETTER}({LETTER}|{DIGIT})*

%%

{WS}+           {}
{NEW_LINE}      { ++lineno; }
{NUMBER}        { sscanf (yytext, "%d", &tokenval); return(NUM); }
{ID}            { sscanf (yytext, "%s", &tokenval); return(ID); }
.               { return *yytext;}
<<EOF>>         { return (DONE); }

%%

并在 global.h 中定义

#define BSIZE 128
#define NONE -1
#define EOS '\0'
#define NUM 256
#define DIV 257
#define MOD 258
#define ID  259
#define DONE 260

当我使用数字、括号和运算符时一切正常,但是当我输入例如 a+b 时,它会给我 Segmentation fault(并且输出应该是 ab+). 请不要向我索要解析器代码(如果确实需要,我可以分享)- 要求是仅使用 Flex 实现词法分析器。

最佳答案

问题是程序正在执行一个 sscanf string 格式 (%s) 到整数地址 (&tokenval)。您应该将其更改为 char 数组,例如,

%{
    #include "global.h"
    int lineno = 1;
    int tokenval = NONE;
    char tokenbuf[132];
%}

{ID}            { sscanf (yytext, "%s", tokenbuf); return(ID); }

(尽管 strcpy 是比 sscanf 更好的选择,但这只是一个起点)。

关于c - ID 的 Flex 模式给出 'Segmentation fault',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30696916/

相关文章:

regex - 如何使用正则表达式删除第二次出现字符以外的所有内容?

java - 使用 java.util.scanner.hasNext(regex) 获取整行

regex - Vim 正则表达式替换问题

regex - 如何在 cpplint 中使用 exclude_files 正则表达式?

javascript - 用空 javascript 替换 <xml> 标签数据

c - 尝试使用指针从字符串中删除字符

c - 有符号整数溢出 : 1111111111111111111 * 10 cannot be represented in type 'long long'

c - 直接声明并赋值给 C 指针

c - IRC 程序不打印最后一条消息

c - 如何使用 CMake post_build 执行 shell 脚本?