動的に割り振られた記憶域の管理

ILE では、ヒープを管理することによってプログラムから実行時記憶域を 直接管理することができます。ヒープは動的記憶域の割り振りに使用される記憶域のことです。 アプリケーションに必要な動的記憶域の量は、 ヒープを使用するプログラムおよびプロシージャーによって処理されるデータによって異なります。

ヒープを管理するために、以下を使用できます。

実行時記憶域を明示的に管理する必要はありません。 しかし、動的に割り振られた実行時記憶域を使用したい場合には、明示的に管理することができます。 例えば、配列または複数回繰り返しデータ構造の大きさをどれぐらいにすべきか正確には分からない場合に、 明示的に管理することができます。 配列またはデータ構造を BASED と定義し、プログラムがこれらの大きさを決定した時に、 配列またはデータ構造の実際の記憶域を獲得することができます。

図 52. 動的に割り振られた配列の割り振り、ソートおよび検索
 * Two counters are kept:
 * 1. The current number of array elements
 * 2. The number of array elements that are allocated for the array
D arrInfo         DS                  QUALIFIED
D   pArr                          *   INZ(*NULL)
D   numElems                    10I 0 INZ(0)
D   numAlloc                    10I 0 INZ(0)
D arr             S             20A   VARYING DIM(32767)
D                                     BASED(arrInfo.pArr)
D i               S             10I 0
 /free
    // Allocate storage for a few array elements
    // (The number of elements that the array is considered to
    // actually have remains zero.)
    arrInfo.numAlloc = 2;
    arrInfo.pArr = %alloc(arrInfo.numAlloc * %size(arr));

    // Add two elements to the array
    if arrInfo.numAlloc < arrInfo.numElems + 2;
      // There is no room for the new elements.
      // Allocate a few more elements.
      arrInfo.numAlloc += 10;
      arrInfo.pArr = %realloc (arrInfo.pArr
                             : arrInfo.numAlloc * %size(arr));
              endif;
    arrInfo.numElems += 1;
    arr(arrInfo.numElems) = 'XYZ Electronics';
    arrInfo.numElems += 1;
    arr(arrInfo.numElems) = 'ABC Tools';

    // Search the array
    i = %lookup ('XYZ Electronics' : arr : 1 : arrInfo.numElems);
    // i = 1

    // Sort the array
    sorta %subarr(arr : 1 : arrInfo.numElems);

    // Search the array again
    i = %lookup ('XYZ Electronics' : arr : 1 : arrInfo.numElems);
    // Now, i = 2, since the array is now sorted

    // Remove the last element from the array
    arrInfo.numElems -= 1;

    // Clear the array
    // This can be done simply by setting the current number of
    // elements to zero.  It is not necessary to actually clear
    // the data in the previously used elements.
    arrInfo.numElems = 0;

    // Free the storage for the array
    dealloc arrInfo.pArr;
    reset arrInfo;

    return;

システムでは、デフォルト・ヒープとユーザー作成ヒープの 2 種類のヒープを 使用することができます。RPG 記憶域管理命令は、デフォルト・ヒープを使用します。 これ以降の節では、デフォルト・ヒープで RPG 記憶域管理命令を 使用する方法、および記憶域管理 API を使用して独自の ヒープを作成して使用する方法について説明します。 ユーザー作成のヒープ、 およびその他の ILE 記憶域管理の概念について詳しくは、「ILE 概念」を参照してください。