dynamic-memory-here

Dynamic memory allocation in the data space region



include dynamic-memory-here.fs

\ make an object and its "variable" storage:
variable pObj1
100 malloc pObj1 !  \ 100 address units have been allocated at 'here'

\ make a second "variable":
variable pObj2

\ define some words to dump state:
: dd dup . ." -> " @ . cr ;
: d(
  cr postpone .( cr
  base @ hex
  ." pObj1: @" pObj1 dd
  ." pObj2: @" pObj2 dd
  ."  here: @" here . cr
  ." bubbles:" cr
  _bub_list
  begin
    @ dup
  while
    dup . ." -> " dup cell+ @ . cr
  repeat
  drop
  base !
;
d( Allocated Obj1: )

\ space for Obj2:
200 malloc pObj2 !
d( Allocated Obj2: )

\ grow Obj1
pObj1 @ 200 mresize pObj1 !
d( Grew Obj1: )

\ shrink Obj2
pObj2 @ 50  mresize pObj2 !
d( Shrank Obj2: )

\ free the second (and forget its pointer)
pObj2 @ mfree
0 pObj2 !
d( Freed Obj2: )

\ free the first (again, forgetting)
pObj1 @ mfree
0 pObj1 !
d( Freed Obj1: )

bye

by JimPeterson

avatar of JimPeterson

Versions

1.0.0

Download current as zip

Tags

forth-2012, memory, allocation

Dependencies

None

Dependents

None