简体   繁体   English

lex 程序有一个错误,但我不知道它是什么?

[英]there is an error on the lex program but i don't know what is it?

I write this lex program but there is an error if you can check my code because i check it a lot, but i didn't find it.我编写了这个 lex 程序,但是如果您可以检查我的代码,则会出现错误,因为我检查了很多,但我没有找到它。

This is the code:这是代码:

%{
    #include <stdio.h>
    #include <string.h>
    
    int WordLength=0;
    char LongestWord[200];
    
    int arrayIndex=0;
    double num[2000]={0};
    
    int numofvowel=0;
    char VowelArray[100][100];
    
    int IngNum=0;
    
    int numLine=0;
%}

%%

[aeiouAEIOU][a-zA-Z]+  {strcpy(VowelArray[numofvowel],
    yytext);numofvowel+=1;}
    
[.+ing]+ {IngNum+=1;}
    
[0-9]+    {if(atof(yytext) > 500) 
    {num[arrayIndex]=atof(yytext);arrayIndex+=1;}  }
    
[a-zA-Z]+ {if (yyleng > WordLength)
              {
                  WordLength=yyleng;
                  strcpy(LongestWord,yytext);
                  }
              }
    
[/n]      {numLine++;}
    
. ;
    
%%
    
int yywrap(){
    return 1;}
    
int main(int argc[] , char **argv[]){
    char file[] = "";
    printf("Enter the file name : ");
    scanf("%s", file);
    extern FILE *yyin ;
    yyin=fopen(file, "r");
    yylex();
    
    printf("The longest word is %s ",LongestWord);
    
    printf("/n");
    
    printf("The numbers that are greater than 500 are: ");
    for(int i=0 ; i<arrayIndex ; i++){
    printf("%f, ",num[i]);}
    
    printf("There are %d words that start with vowel letter. They
    are:",numofvowel);
    for (int k = 0; k < numofvowel; k++){
        printf("%s, ", VowelArray[k]);}
    
    printf("The number of words that are ended by ”ing”: %d ",IngNum);
    
    printf("The number of lines %d ",numLine);
    return 0;
}

This error appears:出现此错误:

*** stack smashing detected ***: terminated
Aborted (core dumped)

The error is caused by the few first lines of the main function.该错误是由main function的几行引起的。

Here is a minimal example that causes it:这是导致它的最小示例:

#include <stdio.h>
int main(){
    char file[] = "";
    scanf("%s", file);
}

This code creates variable file that is only big enough to fit an empty string inside but the function scanf attempts to put a longer string inside.此代码创建的变量file仅大到足以容纳其中的空字符串,但 function scanf尝试将更长的字符串放入其中。

A fast and unsafe solution would be to just increase the size of the buffer file , eg:一个快速且不安全的解决方案是只增加缓冲区file的大小,例如:

    char file[100];  // No need to initialize it since scanf will overwrite it anyway.

If you want something more reliable (and you probably should), here are the best practices on avoiding such problems with scanf : How to prevent scanf causing a buffer overflow in C?如果您想要更可靠的东西(并且您可能应该),以下是避免scanf此类问题的最佳实践:如何防止 scanf 在 C 中导致缓冲区溢出? . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM