3.3. Dynamic allocation


The problem

The new command in Pascal does not allow you to choose how much memory to allocate at run time; thus when creating an array you must choose an upper bound in advance. This presents problems when for example you need 200 lists with a maximum total size of 60000 bytes. Since each array could be up to 60000 bytes by itself, you would need to allocate 60000 bytes to each array. This is clearly not practical. The usual solution in this case is to use linked lists. However, linked lists are not well suited to all applications, have a high memory overhead and are usually slow to work with. They are also more difficult to write and debug.


The solution

The solution is dynamic allocation, which means to allocate to each array only as much memory as it needs at run time. This will be old news to C programmers who are basically forced to do this using the malloc command. In Pascal you need to use the getmem and freemem commands.


Implementation

type
    integer_array = array[1..30000] of integer;
    integer_pointer = ^integer_array;
var
   the_pointer : integer_pointer;    {pointer to access the array}
   number : integer;                 {actual number of items}
begin
     {get the actual number of items}
     getmem(the_pointer, number * sizeof(integer));
     {do stuff with the the_pointer^ array}
     freemem(the_pointer, number * sizeof(integer));
end.

This code illustrates how to dynamically allocate memory for the array. Note that although the upper limit of 30000 is arbitrary: the actual limit is number, and it is up to you to make sure that you never use a higher index (otherwise some really weird stuff can happen). You should make the arbitrary limit as high as possible to prevent range check errors that will result if the error checker thinks you are trying to access something that is out of bounds (the range checker doesn't know about dynamic allocation). You must also make sure that the freemem command specifies the same amount of memory as the getmem command.


Resizing

It is not possible to directly resize a dynamically allocated array. You must allocate a new array, copy the data into the new array and free the old array.

Because of this, it may sometimes be necessary to make an initial pass of the input file to determine how much memory to allocate to each array before doing the main pass to fill the arrays with data.


[Prev] [Next] [Up]

Last updated Sun Nov 28 22:04:38.0000000000 2004. Copyright Bruce Merry (bmerry '@' gmail dot. com).