0

Okay I have the following code in Bison .l file. By the way I am new to c.

exp: TK_SLIT    // TK_SLIT is a string literal token

      /* assigns the type to the nonterminal exp */
      $$ ->type = (char *) malloc (strlen ("string") + 1);  /* allocates space */
      strcpy ($$->type,"string");  /* puts value in there */ 
      printf ("%s\n",$$->type);

      printf ("The value of TK_SLIT is - %s\n",$1);

I have figured out that the "assigns type" block of code (4 lines including comment) OVERWRITES the value of TK_SLIT ($1) in memory. The value of TK_SLIT was grabbed from my scanner, FLEX.

I know that the block of code is causing the problem because if I comment out the "assigns type" block of code, then my TK_SLIT token value prints just fine. Otherwise it becomes garbled characters.

Is there something wrong with my malloc? Why is it overwriting my token value? Is this a bison issue where it's not protecting my token values in memory?

Okay my union is as follows:

%union
{

    int intbison;
    char *charbison; // used for input
    char *boolbison;
    int voidbison;
    charlist *charlistbison;
    arraylist *arraylistbison;
    expnode *expnodebison;
}

Also here is my expnode from the header file:

   typedef struct expnode{
        char *type;
        typesymrec *typesymrecptr;
        varsymrec *varsymrecptr;
        char *stringval;
        int intval;
        int boolval;


}expnode;

And I made "exp" nonterminal the "expnodebison" type.

Lesmana
  • 25,663
  • 9
  • 82
  • 87
Kt Mack
  • 381
  • 4
  • 17

1 Answers1

1

Finally figured it out.

The problem was that the $$ was an expnode struct type, and this needed to be malloc'd.

Once I did this, my TK_SLIT $1 token was preserved. Below is the fix

exp: TK_SLIT    // TK_SLIT is a string literal token

    $$ = (expnode *) malloc (sizeof (expnode));
    $$ ->type = (char *) malloc (strlen ("string") + 1);  /* allocates space */
    strcpy ($$->type,"string");  /* puts value in there */ 
    printf ("%s\n",$$->type);

    printf ("The value of TK_SLIT is - %s\n",$1);


}
Kt Mack
  • 381
  • 4
  • 17