Thursday, April 12, 2012

Bison token value overwritten - c memory issues?

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?

1 comment:

  1. I don't know if this will actually solve your problem but you might want to try to change your call to malloc() to this:

    malloc (sizeof(char) * (strlen ("string") + 1));