From fc47bf214377ef07cb499928dbf8ee390e5613be Mon Sep 17 00:00:00 2001 From: Garritt McCune Date: Thu, 5 May 2022 20:10:10 +0000 Subject: [PATCH] Fixed up the code a bit and fixed a memory leak bug (of course, there's still no good way to free Tokens but that'll be sorted out later). --- src/main.c | 2 +- src/scanner.c | 19 ++++++++++++++----- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/main.c b/src/main.c index e3aa244..5d04ffa 100644 --- a/src/main.c +++ b/src/main.c @@ -26,7 +26,7 @@ int main(int argc, char* args[]) { Token* t = (Token*) list->content[i]; printf("[%i] '%s'", t->type, t->lexeme); - if (t->type == NUMBER || t->type == HEX) printf(" NUM: %ld", (long) t->value); + if (t->type == NUMBER || t->type == HEX) printf(" NUM: %ld", *((long *) t->value)); printf("\n"); } diff --git a/src/scanner.c b/src/scanner.c index 1b92524..7426131 100644 --- a/src/scanner.c +++ b/src/scanner.c @@ -1,4 +1,6 @@ #include "../includes/scanner.h" +#include +#include const char* SourceCode; int Line = 0; @@ -93,20 +95,26 @@ Token* ParseNumber(void) { if (length == 0) return NULL; char* lexeme = calloc(sizeof(char), length + 1); + long* value = calloc(1, sizeof(long)); if (!lexeme) { fprintf(stderr, "Failed to calloc space for number. %s.\n", strerror(errno)); return NULL; } + if (!value) { + free(lexeme); + fprintf(stderr, "Failed to calloc space for the raw numeric value of a token. %s.\n", strerror(errno)); + return NULL; + } + memcpy(lexeme, &SourceCode[start], length); - //Setting the base to zero means the function will detect the base. - //https://pubs.opengroup.org/onlinepubs/7908799/xsh/strtol.html - printf("Number Parsed: %s (%ld)\n", lexeme, strtol(lexeme, NULL, 0)); + + *value = strtol(lexeme, NULL, base); - if (base == 10) return CreateToken(lexeme, lexeme, Line, NUMBER); + if (base == 10) return CreateToken(lexeme, value, Line, NUMBER); - return CreateToken(lexeme, lexeme, Line, HEX); + return CreateToken(lexeme, value, Line, HEX); } Token* ParseDirective(void) { @@ -132,6 +140,7 @@ Token* ParseDirective(void) { } else if (strcmp(directive, ".org") == 0) { fprintf(stderr, "[Warning] Org is not a supported directive.\n"); + free(directive); IgnoreLine(); return NULL; }