You can create a global variable v with
v pushes the address of a cell in memory on the stack. This
cell was reserved by variable. You can use ! (store) to
store values from the stack into this cell and @ (fetch) to
load the value from memory onto the stack:
You can see a raw dump of memory with dump:
Cells ( n1 -- n2 ) gives you the number of bytes (or, more
generally, address units (aus)) that n1 cells occupy. You can
also reserve more memory:
creates a variable-like word v2 and reserves 20 uninitialized
cells; the address pushed by v2 points to the start of these 20
cells (see CREATE). You can use address arithmetic to access
these cells:
You can reserve and initialize memory with ,:
Assignment: Write a definition
vsum ( addr u -- n )that computes the sum ofucells, with the first of these cells ataddr, the next one ataddr cell+etc.
The difference between variable and create is that
variable allots a cell, and that you cannot allot additional
memory to a variable in Standard Forth.
You can also reserve memory without creating a new word:
The first here pushes the start address of the memory area, the
second here the address after the dictionary area. You should
store the start address somewhere, or you will have a hard time
finding the memory area again.
Allot manages dictionary memory. The dictionary memory contains
the system’s data structures for words etc. on Gforth and most other
Forth systems. It is managed like a stack: You can free the memory that
you have just alloted with
Note that you cannot do this if you have created a new word in the
meantime (because then your alloted memory is no longer on the
top of the dictionary “stack”).
Alternatively, you can use allocate and free which allow
freeing memory in any order:
The throws deal with errors (e.g., out of memory).
And there is also a
garbage collector, which eliminates the need to free memory
explicitly.
Reference: Memory.