Fix memory leak(require further fining)

This commit is contained in:
Night Kaly 2025-01-21 03:55:53 +00:00
parent 7ccc3e32ba
commit 2219cab59e
Signed by: night0721
SSH key fingerprint: SHA256:B/hgVwUoBpx5vdNsXl9w8XwZljA9766uk6T4ubZp5HM
3 changed files with 14 additions and 7 deletions

View file

@ -4,11 +4,11 @@
#include "ast.h"
#include "lexer.h"
typedef struct ht_t {
struct ht_t {
char *name;
value_t value;
struct ht_t *enclosing;
} ht_t;
};
#define DEFAULT_HT_SIZE 500

View file

@ -69,6 +69,9 @@ value_t *ht_get(ht_t *ht, token_t *name, int check_enclosing)
memcpy(val, &ht[probe_idx].value, sizeof(value_t));
if (val->type == VAL_STRING) {
val->as.string = strdup(ht[probe_idx].value.as.string);
} else if (val->type == VAL_FN) {
val->as.function = malloc(sizeof(fn_t));
memcpy(val->as.function, ht[probe_idx].value.as.function, sizeof(fn_t));
}
return val;
@ -101,11 +104,16 @@ void ht_replace(ht_t *ht, char *name, value_t *value)
if (!strcmp(ht[probe_idx].name, name)) {
if (ht[probe_idx].value.type == VAL_STRING) {
free(ht[probe_idx].value.as.string);
} else if (ht[probe_idx].value.type == VAL_FN) {
free(ht[probe_idx].value.as.function);
}
ht[probe_idx].value.type = value->type;
ht[probe_idx].value.as = value->as;
if (value->type == VAL_STRING) {
ht[probe_idx].value.as.string = strdup(value->as.string);
} else if (value->type == VAL_FN) {
ht[probe_idx].value.as.function = malloc(sizeof(fn_t));
memcpy(ht[probe_idx].value.as.function, value->as.function, sizeof(fn_t));
}
return;
}

View file

@ -26,7 +26,9 @@ void free_val(value_t *value)
free(value->as.string);
}
} else if (value->type == VAL_FN) {
if (value->as.function) {
free(value->as.function);
}
}
free(value);
}
@ -476,9 +478,7 @@ void evaluate_statement(stmt_t *stmt, ht_t *env, return_state_t *state)
}
case STMT_BLOCK:;
ht_t *cp_env = ht_init(env);
evaluate_block(stmt->as.block.statements, env, cp_env, state);
/* ht_free(cp_env); */
evaluate_block(stmt->as.block.statements, env, ht_init(env), state);
break;
case STMT_WHILE:;
@ -507,7 +507,6 @@ void evaluate_statement(stmt_t *stmt, ht_t *env, return_state_t *state)
fn_val->as.function = fn;
ht_add(env, stmt->as.function.name.value, fn_val);
free_val(fn_val);
free(fn);
break;
case STMT_RETURN:;