Memory management in Forth

前端 未结 5 437
有刺的猬
有刺的猬 2021-02-02 16:47

So I\'m just learning Forth and was curious if anyone could help me understand how memory management generally works. At the moment I only have (some) experience with the C stac

5条回答
  •  灰色年华
    2021-02-02 17:17

    Peter Mortensen laid it out very well. I'll add a few notes that might help a C programmer some.

    The stack is closest to what C terms "auto" variables, and what are commonly called local variables. You can give your stack values names in some forths, but most programmers try to write their code so that naming the values is unnecessary.

    The dictionary can best be viewed as "static data" from a C programming perspective. You can reserve ranges of addresses in the dictionary, but in general you will use ALLOT and related words to create static data structures and pools which do not change size after allocation. If you want to implement a linked list that can grow in real time, you might ALLOT enough space for the link cells you will need, and write words to maintain a free list of cells you can draw from. There are naturally implementations of this sort of thing available, and writing your own is a good way to hone pointer management skills.

    Heap allocation is available in many modern Forths, and the standard defines ALLOCATE, FREE and RESIZE words that work like malloc(), free(), and realloc() in C. The memory they return is from the OS system heap, and it's generally a good idea to store the address in a variable or some other more permanent structure than the stack so that you don't inadvertently lose the pointer before you can free it. As a side note, these words (along with the file i/o words) return a status on the stack that is non-zero if an error occurred. This convention fits nicely with the exception handling mechanism, and allows you to write code like:

    variable PTR
    1024 allocate throw PTR !
    \ do some stuff with PTR
    PTR @ free throw
    0 PTR !
    

    Or for a more complex if somewhat artificial example of allocate/free:

    \ A simple 2-cell linked list implementation using allocate and free
    : >link ( a -- a ) ;
    : >data ( a -- a ) cell + ;
    : newcons ( a -- a )    \ make a cons cell that links to the input
       2 cells allocate throw  tuck >link ! ;
    : linkcons ( a -- a )   \ make a cons cell that gets linked by the input
       0 newcons dup rot >link ! ;
    : makelist ( n -- a )   \ returns the head of a list of the numbers from 0..n
       0 newcons  dup >r
       over 0 ?do
         i over >data ! linkcons ( a -- a )
       loop  >data !  r> ;
    : walklist ( a -- )
       begin   dup >data ?  >link @           dup 0= until drop ;
    : freelist ( a -- )
       begin   dup >link @  swap free throw   dup 0= until drop ;
    : unittest  10 makelist dup walklist freelist ;
    

提交回复
热议问题