commit e39faa528865d7a5109c9631bbb33f13dc29cb49
parent 0cc603389b08252b018c330f35c9e16075ff7e17
Author: citbl <citbl@citbl.org>
Date: Tue, 12 May 2026 20:29:39 +1000
fixes
Diffstat:
3 files changed, 35 insertions(+), 9 deletions(-)
diff --git a/src/lexer.c b/src/lexer.c
@@ -3,14 +3,19 @@
#include <ctype.h>
#include "lexer.h"
-#include "str.h"
static void add_token(Lexer* lex, Token t)
{
+ size_t new_cap;
+ Token* p;
+
if (lex->len >= lex->cap) {
- lex->cap = lex->cap == 0 ? 256 : lex->cap * 2;
- lex->tokens = realloc(lex->tokens, lex->cap * sizeof(Token));
- check(lex->tokens == NULL, "could not allocate memory for the tokens\n");
+ new_cap = lex->cap == 0 ? 256 : lex->cap * 2;
+ check(new_cap <= lex->cap || new_cap > SIZE_MAX / sizeof(Token), "token capacity overflow\n");
+ p = realloc(lex->tokens, lex->cap * sizeof(Token));
+ check(!p, "token reallocation failed\n");
+ lex->tokens = p;
+ lex->cap = new_cap;
}
lex->tokens[lex->len++] = t;
diff --git a/src/str.c b/src/str.c
@@ -4,11 +4,18 @@
void str_append(Str* str, const char c)
{
+ size_t new_cap;
+ char* s;
+
if (str->len >= str->cap) {
- str->cap = str->cap == 0 ? 32 : str->cap * 2;
- str->value = realloc(str->value, str->cap * sizeof(char));
- check(str->value == NULL, "str_append: could not alloc string\n");
+ new_cap = str->cap == 0 ? 32 : str->cap * 2;
+ check(new_cap <= str->cap || new_cap > SIZE_MAX / sizeof(Str), "could not reallocate string\n");
+ s = realloc(str->value, new_cap * sizeof(char));
+ check(s == NULL, "str_append: could not alloc string\n");
+ str->cap = new_cap;
+ str->value = s;
}
str->value[str->len++] = c;
+ str->value[str->len] = '\0'; // important!
}
diff --git a/src/utils.c b/src/utils.c
@@ -8,17 +8,31 @@ char* read_file(const char* filename)
{
long fsize;
char* source;
- FILE* fp = fopen(filename, "r");
+ FILE* fp = fopen(filename, "rb");
if (fp == NULL) {
fprintf(stderr, "file not found\n");
return NULL;
}
- fseek(fp, 0, SEEK_END);
+ if (fseek(fp, 0, SEEK_END) != 0) {
+ fprintf(stderr, "could not read file\n");
+ fclose(fp);
+ exit(1);
+ }
+
fsize = ftell(fp);
+ if (fsize < 0) {
+ fprintf(stderr, "could not read size of file to load\n");
+ fclose(fp);
+ exit(1);
+ }
fseek(fp, 0, SEEK_SET);
source = malloc(fsize + 1);
+ if (!source) {
+ fprintf(stderr, "could not allocate memory to read file\n");
+ exit(1);
+ }
fread(source, fsize, 1, fp);
fclose(fp);