For the code below, I am going to read tokens, for example, x, y, and z, and allocate them into a list of tokens' lexeme. The code is shown below:
int parse_varlist(void)
{
token = lexer.GetToken();
char* lexeme = (char*)malloc(sizeof(token.lexeme) + 1);
memcpy(lexeme, (token.lexeme).c_str(), (token.lexeme).size() + 1);
addList(lexeme); //This function is used to add tokens' lexeme into a
list
if (token.token_type == ID) //ID is token's type
{
token = lexer.GetToken(); //read next token
parse_varlist(); //let parse_varlist() call itself to add
tokens' lexeme into list
printList(); // print list of token's lexeme
}
else {
cout << "\n Syntax Error \n";
}
free(lexeme);
return(0);
}
// this is the code of addList():
void addList(char* lexeme) {
if (symbolTable == NULL) {
sTable* newEntry = (sTable *)malloc(sizeof(sTable));
sTableEntry* newItem = (sTableEntry *)malloc(sizeof(sTableEntry));
newItem->name = lexeme;
newEntry->next = NULL;
newEntry->prev = NULL;
symbolTable = newEntry;
}
Suppose we are going to read x, y and store their lexeme into the list. Currently, I can get these two tokens. But, after calling printList() I can only have x in my list.
I checked the possible solution online. I may use calloc() instead malloc() to allocated these memory? But, for the list that I am trying to create, am I allocating the memory into a single block or multiple block? Since this is one significant between calloc() and malloc():