I am writing a software in C. For that purpose I use lex. I wrote a piece of code in C to create a symbol table and manage it. So, whenever lex finds a new symbol, it puts it in a symbol table. Problem is, when I try to print all results from symbol table, I get output I didn’t expect.
If, for example, the input file was:
int main(){}
the output should be:
int
main
(
)
{
}
but the output is:
int main(){}
main(){}
(){}
...
and so on.
The function used for printing is something like this
void print_entries(struct symtab *start) {
struct symtab *s = start;
while(s != NULL) {
printf("%s\n", s->name);
s = s->next;
}
}
Here is the code for adding new symbols:
void add_entry(char* name, int type, struct symtab *start)
{
struct symtab *new;
new = malloc(sizeof(struct symtab));
last_entry(start)->next = new;
new->name = name;
new->type = type;
new->next = NULL;
}
Any ideas?
You need to copy the symbol names into the symbol table entries. If for some peculiar reason your system does not have
strdup()already, then use:(In this context, I could use
memcpy()safely; I usememmove()because it always works andmemcpy()does not. And I usememmove()because I know exactly how long the string is so the copy doesn’t need to test each character for nullness as it goes.)With
strdup()on hand:Note that this still omits the error checking from the two memory allocations, which is not a good habit to get into. I’ve revised it to use
symrather thannewbecause the latter is a C++ keyword and I avoid using those as identifiers, even in C code.