-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken.c
More file actions
28 lines (26 loc) · 971 Bytes
/
token.c
File metadata and controls
28 lines (26 loc) · 971 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "token.h"
#include <stdlib.h> // for malloc
#include <string.h>
// allocates memory on the heap to the struct Token and then returns the address of its memory space
Token* create_token(TokenType type, const char* lexeme){
Token* token = (Token*)malloc(sizeof(Token));
if (token == NULL){ //pointer is null meaning we failed to allocate the memory
perror("failed to allocate memory for the token");
exit(EXIT_FAILURE);
}
token->type=type;
token->lexeme=strdup(lexeme); //using strdup over strcpy coz that manages the memory as well
if (token->lexeme==NULL){
perror("Failed ot duplicate the string");
free(token);
exit(EXIT_FAILURE);
}
return token;
};
//freeing a token after its use is done.
void free_token(Token* token){
if (token){
free(token->lexeme); // first free the duplicated string
free(token); // then duplicating the
}
};