0

This is my code

strcpy doesnt copy the yytext

Any suggestion why?

These are my globals

char** v; /* array of variables and their values */
int i;

some name definition

WORD    [a-zA-Z]
DIGIT   [0-9]

These are the states

<VAL>"\"".+"\"" {int x=sizeof(yytext);
    v[i]=(char*)realloc(v, x*sizeof(char));
        strcpy(v[i],yytext);
    i++;
    BEGIN(INITIAL);}
<VAL>.  { i--;printf("error");}
<SAVE_VAL>{WORD}[{WORD}{DIGIT}_]*   { 
    if (NULL==v){
        v=(char**)realloc(v, 100*sizeof(char*));
        i=0;
    }
    int x=sizeof(yytext);
    v[i]=(char*)realloc(v, x+2);
    strcpy(v[i],yytext);
    i++;
    BEGIN(VAL);
    }

val" " {BEGIN(SAVE_VAL);}

This is the yywrap

int yywrap(void){
    return 1;

}

This is the main

int main(void) { 

    yyin=fopen("input.txt","r");   
    yylex();
    fclose(yyin); 

This is the loop to print the strings

    for (int j=0;j<100;j++){
        if (NULL==v[j])
            break;
        printf("%s",v[j],i);
    }
} 


}

I'm tring to run it on val a="asdasd";

I'm expecting it to print a asdasd

Brian
  • 3,850
  • 3
  • 21
  • 37
mosheovadi1
  • 73
  • 12

1 Answers1

3

This:

int x=sizeof(yytext);

doesn't do what you think it does. yytext is of type char*; that is, it is a pointer to a character. That means that sizeof yytext is either 4 or 8, depending on whether you're compiling on a 32-bit or 64-bit platform. (Or some other pointer length if you have a really unusual architecture.)

It is not the length of the string starting at yytext. That would be the standard library function strlen(yytext).

However, you don't need to use that, either, because flex has helpfully assigned the length of the token to the global variable yyleng.

When you are allocating space for the copy, don't forget that in C strings are always NUL-terminated. That means that the allocation for a string must be (at least) one greater than the length of the string, which means you need yyleng + 1 bytes.

rici
  • 234,347
  • 28
  • 237
  • 341