Memory allocation

From Rosetta Code
Revision as of 16:37, 26 May 2009 by rosettacode>IanOsgood (new task: Memory Allocation)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Memory allocation
You are encouraged to solve this task according to the task description, using any language you may know.

Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e. heap, stack, shared, foreign) if applicable.

C

TODO: malloc() and free()

Forth

Forth has two main bulk memory areas, each with their own word sets and semantics for allocation and deallocation.

Dictionary

All Forth implementations have a stack-like memory space called the dictionary. It is used both for code definitions and data structures. <lang forth> unused . \ memory available for use in dictionary here . \ current dictionary memory pointer

mem, ( addr len -- ) here over allot swap move ;
s, ( str len -- ) here over char+ allot place align ; \ built-in on some forths
," [char] " parse s, ;

variable num create array 60 cells allot create struct 0 , 10 , char A c, ," string" unused . here . </lang>

Dictionary space is meant for static code definitions and supporting data structures, so it is not as easy to deallocate from it. For ad-hoc allocations without intervening definitions, you may give a negative value to ALLOT to reclaim the space. You may also lay down a named MARKER to reclaim the space used by all subsequent definitions. <lang forth> marker foo

temp ... ;

create dummy 300 allot -150 allot \ trim the size of dummy by 150 bytes foo \ removes foo, temp, and dummy from the list of definitions </lang>

Heap

Most Forth implementations also give access to a larger random-access memory heap. <lang forth>

 4096 allocate throw  ( addr )
 dup 4096 erase
 ( addr ) free throw

</lang>

Oberon-2

TODO:

Pascal

TODO: