summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Phillips <david@sighup.nz>2019-08-11 17:30:54 +1200
committerDavid Phillips <david@sighup.nz>2019-08-11 19:47:05 +1200
commit07af05ccc60e1aec3e8dd501233d67eaf769a8e7 (patch)
tree56fae0ab798cb9b8852810efd6d02524ed4c273a
parent2d2628df0001d2b643811dc69717c4afe70c4e31 (diff)
downloadtoy-cpu-assembler-07af05ccc60e1aec3e8dd501233d67eaf769a8e7.tar.xz
Don't ignore ret variables, remove memory leak on add_token failure
-rw-r--r--input/input_bin.c2
-rw-r--r--lex.c54
2 files changed, 33 insertions, 23 deletions
diff --git a/input/input_bin.c b/input/input_bin.c
index eafcca1..c80e0b4 100644
--- a/input/input_bin.c
+++ b/input/input_bin.c
@@ -188,7 +188,7 @@ read_eof:
perror("fread");
ret = -errno;
}
- return 0;
+ return ret < 0 ? ret : 0;
}
int input_bin(FILE *f, struct instruction **i, size_t *i_count)
diff --git a/lex.c b/lex.c
index 29cd8c2..c275d19 100644
--- a/lex.c
+++ b/lex.c
@@ -35,6 +35,24 @@ static int expect(const char c) {
return 0;
}
+void lex_free_tok(struct token t)
+{
+ if (t.s_val)
+ free(t.s_val);
+
+}
+
+void lex_free(struct token *ts, size_t t_count)
+{
+ size_t i = 0;
+
+ for (i = 0; i < t_count; i++) {
+ lex_free_tok(ts[i]);
+ }
+
+ free(ts);
+}
+
static void store_location(struct token *t) {
t->column = column + 1;
t->line = line + 1;
@@ -305,6 +323,7 @@ static int lex_eof(struct token *t) {
int lex_line(void) {
int ret = 0;
+ int final = 0;
size_t len = strlen(buffer);
struct token tok;
@@ -331,7 +350,8 @@ int lex_line(void) {
case '!':
case '\n':
ret = lex_eol(&tok);
- return add_token(tok);
+ final = 1;
+ break;
case ' ':
case '\t':
eat_whitespace();
@@ -344,7 +364,7 @@ int lex_line(void) {
} else if (column + 1 < len && buffer[column + 1] == '/') {
ret = lex_eol(&tok);
column += 2;
- return add_token(tok);
+ final = 1;
} else {
emit("Unexpected '/'\n");
return 1;
@@ -379,30 +399,20 @@ int lex_line(void) {
break;
}
if (ret)
- return ret;
+ goto exit_free;
- if (add_token(tok))
- return 1;
- }
- return 0;
-}
-
-void lex_free_tok(struct token t)
-{
- if (t.s_val)
- free(t.s_val);
-
-}
-
-void lex_free(struct token *ts, size_t t_count)
-{
- size_t i = 0;
+ ret = add_token(tok);
+ if (ret)
+ goto exit_free;
- for (i = 0; i < t_count; i++) {
- lex_free_tok(ts[i]);
+ if (final)
+ return ret;
}
- free(ts);
+exit_free:
+ if (ret)
+ lex_free_tok(tok);
+ return ret;
}
struct token* lex(const char *filename_local, FILE *fin, size_t *len)