aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoronelin <oscar@nelin.dk>2026-09-22 20:46:24 +0000
committeronelin <oscar@nelin.dk>2026-09-22 20:46:24 +0000
commita7393edb53560cfafb213eaf9e6d11af55c33047 (patch)
treed6add0f502d8fe42a47ddda8642fb64bc2306dcf
parent5b29903b6370a5fbca89ac305c865f1956848ee3 (diff)
Fix off-by-one allocation and 0-terminating buffer, amongst memory cleanup
-rw-r--r--main.c18
1 files changed, 14 insertions, 4 deletions
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