From a7393edb53560cfafb213eaf9e6d11af55c33047 Mon Sep 17 00:00:00 2001 From: onelin Date: Tue, 22 Sep 2026 22:46:24 +0200 Subject: Fix off-by-one allocation and 0-terminating buffer, amongst memory cleanup --- main.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) (limited to 'main.c') diff --git a/main.c b/main.c index 5db1a7f..db86d05 100644 --- a/main.c +++ b/main.c @@ -90,6 +90,8 @@ main(int argc, char* argv[]) { // auxilliary structure to keep track of the lines, used for debugging // -- maybe turn off with a flag? line_offsets_t* lines = NULL; + // Resulting AST representing an arithmetic expression + AExp_t* expression = NULL; srcfile = fopen(argv[1], "re"); if (srcfile == NULL) { @@ -130,6 +132,9 @@ main(int argc, char* argv[]) { if (contents != NULL) { free(contents); } + if (expression != NULL) { + free(expression); + } } return 0; } @@ -150,7 +155,7 @@ f_read(FILE* restrict stream, char** restrict dst) { } if (dst != NULL && *dst == NULL && file_sz > 0) { - *dst = (char*)malloc(file_sz * sizeof(char)); + *dst = (char*)malloc((file_sz + 1) * sizeof(char)); } if (dst != NULL && *dst == NULL && file_sz > 0) { @@ -160,7 +165,8 @@ f_read(FILE* restrict stream, char** restrict dst) { usize bytes_read = 0; if (dst != NULL && *dst != NULL && file_sz > 0) { - bytes_read = fread(*dst, sizeof(char), file_sz, stream); + bytes_read = fread(*dst, sizeof(char), file_sz, stream); + dst[bytes_read] = 0; } if (bytes_read < file_sz && feof(stream)) { @@ -325,7 +331,7 @@ l_read(char const* restrict text, usize text_length, static AExp_t* p_arith(char const* restrict text, TokenList_t* restrict tokens) { - i64 exp_idx = 0; + i64 exp_idx = 1; // "groups" or parenthesized expressions // i64 groups = 0; @@ -418,7 +424,11 @@ p_arith(char const* restrict text, TokenList_t* restrict tokens) { exp_idx++; } } - return exp; + + // We store the "root" as the first element, returning a pointer to the + // beginning of the memory also makes it much easier to free. + expression[0] = *exp; + return expression; } static AExp_t -- cgit v1.3