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

Viewed 35

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.

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)
1 Answers

The error is caused by the few first lines of the 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.

A fast and unsafe solution would be to just increase the size of the buffer file, e.g:

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

Related