>>11231>I've found Forth to be a rather inaccessible language unfortunately. >Using memory allocation in Forth is confusing to me.While there is an optional memory allocation word set that provides allocate, free, and resize in the same vein as malloc, free, and realloc (gforth even implements them directly with the C functions) you really shouldn't need them in many cases. Most memory management in Forth should adhere to the stack model.
You should obviously use the data stack for most things and you can even use the return stack, as long as you don't need the values below it, meaning you can use the return stack and call other words without issue. You just need to pop your value from the return stack before you need to return from the word that placed it there.
As for allocating arrays, you should generally use allot when creating a word to associate the space with it. Allot, ,, and c, all use here to determine where the next data space address starts and reserve contiguous space from there.
Here's one way to define an array:
create array 20 allot
Here's one way to create a defining word that defines arrays:
: array ( n "name<space>" -- ) create allot
does> ( n -- addr ) + ;
This word doesn't check array bounds, but this would be easy to add by also storing the length of the array in the newly-defined word and adding a check. All DOES> does is define the behavior of the CREATEd word and places the address of the data space of said word on the stack when being executed. This makes it easy to get the indexed address by simply adding.
I know I went on a tangent really, but I don't really have anyone else to talk to about these things. My main point is memory management in Forth is actually really easy. If you're coming from a GC'd language, you just have to understand that a static memory model isn't that hard to deal with and is usually sufficient. You just have to process certain data in chunks instead of all at once.