diff --git a/forth_words.c b/forth_words.c index 523e392..95987f5 100644 --- a/forth_words.c +++ b/forth_words.c @@ -469,22 +469,18 @@ void do_variable(Word* w) { char* name = next_token(); if (!name) { printf("VARIABLE expects a name\n"); return; } - // allocate a cell for the variable's address - Cell* body_cell = malloc(sizeof(Cell)); - if (!body_cell) { printf("Out of memory\n"); exit(1); } - body_cell->num = here - user_mem; // store the cell index - - // allocate one cell in user memory + // allocate one cell in user memory for the variable's data if (here + 1 > user_mem + user_mem_size) { printf("User memory overflow\n"); - free(body_cell); return; } + Cell* var_cell = here; // address of the data cell + var_cell->num = 0; // initialise to 0 (optional) here++; // create dictionary entry Word* new_w = malloc(sizeof(Word)); - if (!new_w) { printf("Out of memory\n"); free(body_cell); exit(1); } + if (!new_w) { printf("Out of memory\n"); exit(1); } new_w->prev = dict_head; dict_head = new_w; @@ -494,7 +490,7 @@ void do_variable(Word* w) { memcpy(new_w->name, name, len); new_w->name[len] = '\0'; new_w->code = do_do_var; - new_w->body = body_cell; + new_w->body = var_cell; // body points directly to the data cell in user_mem } void do_constant(Word* w) { @@ -503,12 +499,18 @@ void do_constant(Word* w) { char* name = next_token(); if (!name) { printf("CONSTANT expects a name\n"); data_push(val); return; } - Cell* body_cell = malloc(sizeof(Cell)); - if (!body_cell) { printf("Out of memory\n"); exit(1); } - body_cell->num = val; + // allocate a cell in user memory to hold the constant value + if (here + 1 > user_mem + user_mem_size) { + printf("User memory overflow\n"); + data_push(val); // restore the value (optional) + return; + } + Cell* val_cell = here; + val_cell->num = val; + here++; Word* new_w = malloc(sizeof(Word)); - if (!new_w) { printf("Out of memory\n"); free(body_cell); exit(1); } + if (!new_w) { printf("Out of memory\n"); exit(1); } new_w->prev = dict_head; dict_head = new_w; @@ -518,11 +520,12 @@ void do_constant(Word* w) { memcpy(new_w->name, name, len); new_w->name[len] = '\0'; new_w->code = do_do_const; - new_w->body = body_cell; + new_w->body = val_cell; // body points to the cell that holds the value } void do_do_var(Word* w) { - data_push(w->body->num); // push the address (cell index) + // push the address (cell index into user_mem) of the variable's data cell + data_push(w->body - user_mem); } void do_do_const(Word* w) {