Contents | < Browse | Browse >
4K. dynamic memory allocation (NEW)
the NEW operator is a powerful operator for dynamic memory allocation.
it has various forms:
(assuming DEF p:PTR TO whateverobj, q:PTR TO INT)
is an expression that will allocate zero-ised memory for the object-size
p points to. the resulting pointer will be put in p, and is also
the value of the expression. if NEW fails to get memory, it raises
a "NEW" exception. 'NEW p' is therefore roughly equivalent with:
IF (p:=New(SIZEOF whateverobj))=NIL THEN Raise("MEM")
with the difference that p never gets any value if an exception
is raised, and that the former is of course an expression, not
but there's more: it's also possible to allocate an array dynamically:
NEW p /* array of 10 objects */
NEW q[a+1] /* array of INT, size is runtime computed */
(this doesn't work when instantiating classes)
A problem with list [1,2,3] expressions sometimes is that they are static, and
when using these to build large datastructures they would need to be created
at run-time. The dynamic equivalent to static lists may then be used:
p:=[1,2,3]:whateverobj /* static structure */
p:=NEW [1,2,3]:whateverobj /* dynamicly allocated! */
this works with both lists and typed-lists, and also with arrays:
NEW [1,2,3] /* constant-list, dyn. (note: not a like a listvar!) */
NEW [1,2,3]:obj /* object */
NEW [1,2,3]:INT /* array of INTs */
freeing memory allocated with any variations of NEW is done automatically
at the end of the program, or by hand with END or FastDispose().
(note: the only exception is NEW <list>, use FastDisposeList())
If you use NEW [...]:obj, and the number of fields is less than the one
present in the object, additional 0/NIL/"\0" whatever fields will be added.
this allows extending objects without getting into trouble with allocations
like these. (note that this is different from the static [...]:obj)
when you use NEW as a statement, multiple pointers may follow, i.e.:
special forms of NEW and END allow to use a PTR within an object, so you can
write things like
in the examples, the pointer `a' is not affected, the pointer `b' in the `a'
object is used.
NEW allocated lists are not to be used with the Link() functions (see 9H ).
(see 5M , END)
(see 9F for the fast memory allocation functions NEW makes use of)