B
Berk Birand
Hi,
I am working on a school project where we use lex/yacc to write a compiler
for a fictional (Java-like) language. I have handled all the details about
the yacc and lex files, but I still have a question regarding the dynamic
memory allocation for strings. When the lex file encounters a variable
name, I want it to pass this to yacc through yylval, and then
retrieve it to add to a syntax tree. For this purpose, I wrote the
following code in the lex file (third section), that will save the
variable in yylval:
void copy_name(char** dst, char* yy) {
int len;
//free(*dst);
// allocate memory for the new string
len = strlen(yy);
*dst = (char*) malloc(len * sizeof(char) + 1);
// copy the string
strcpy(*dst, yy);
}
It's basically a wrapper around strcpy(), which also allocates some memory
through malloc().
In the lex file, I have something like this
{LETTER}({LETTER}|{DIGIT}|"_")* {copy_name(&(yylval.Name) , yytext);
return(NAME);}
Now my question is whether I should keep the call to free in copy_name or
not. I would think that I need to do that, otherwise new memory would be
allocated each time a new variable is found, and I'd be facing memory
leaks. Yet when I uncomment that line, I start to get segfaults, for
reasons that I can't understand.
Can anybody with more expertise with lex/yacc help me out with this
problem?
Thank you,
Berk Birand
I am working on a school project where we use lex/yacc to write a compiler
for a fictional (Java-like) language. I have handled all the details about
the yacc and lex files, but I still have a question regarding the dynamic
memory allocation for strings. When the lex file encounters a variable
name, I want it to pass this to yacc through yylval, and then
retrieve it to add to a syntax tree. For this purpose, I wrote the
following code in the lex file (third section), that will save the
variable in yylval:
void copy_name(char** dst, char* yy) {
int len;
//free(*dst);
// allocate memory for the new string
len = strlen(yy);
*dst = (char*) malloc(len * sizeof(char) + 1);
// copy the string
strcpy(*dst, yy);
}
It's basically a wrapper around strcpy(), which also allocates some memory
through malloc().
In the lex file, I have something like this
{LETTER}({LETTER}|{DIGIT}|"_")* {copy_name(&(yylval.Name) , yytext);
return(NAME);}
Now my question is whether I should keep the call to free in copy_name or
not. I would think that I need to do that, otherwise new memory would be
allocated each time a new variable is found, and I'd be facing memory
leaks. Yet when I uncomment that line, I start to get segfaults, for
reasons that I can't understand.
Can anybody with more expertise with lex/yacc help me out with this
problem?
Thank you,
Berk Birand