next up previous contents
Next: Practical Use of Pointers Up: Dynamically Allocated Memory and Previous: Pointers   Contents

Allocating and Deallocating Memory

Assuming pointerToInteger is defined as pointer to integer, you can ask the operating system to allocate a piece of memory that fits an integer, and change pointerToInteger to point to that location:

new(pointerToInteger);

This operation, however, overwrites the address previously stored in pointerToInteger.

Once you allocate memory to pointerToInteger, you can refer to the allocated location as pointerToInteger^. In fact, you can treat pointerToInteger^ almost as a variable (and pass it to a passed-by-reference parameter).

When you don't need the integer anymore, you can deallocate the memory using the following statement:

dispose(pointerToInteger;

This statement deallocate the memory location pointed to by pointerToInteger. But it also does not update pointerToInteger so its value becomes NIL. NIL is a pre-defined constant for pointers that indicates that the pointer is pointing to nowhere. You need an explicit assignment statement to make a pointer point to NIL.

You can check if a pointer is pointing to ``nowhere'' using a comparison to NIL:

if pointerToInteger = NIL then
  writeln('the pointer is pointing to nowhere!')
else
  writeln('the pointer points to a location with value ',pointerToInteger^)



Tak Auyeung 2003-12-03