Memory for dynamic variables is allocated off an internal structure called the "heap." The heap is simply a chunk...
of memory that the system allocates for an activation group when the activation group is created.
The Alloc, Dealloc, and Realloc op-codes are pretty straight-forward once you understand a few things about heaps.
- First, a heap is tied to, or scoped to, the activation group in which it was created. Each activation group has one heap called the default heap. The default heap is created automatically when the associated activation group is created. A program can also create additional heaps called user-created heaps using APIs.
- Heaps have an identifier. Since there can be multiple heaps in an activation group, heaps have an ID in order to uniquely identifier them. Many calls to dynamic memory management APIs require a heap identifier parameter to distinguish the heap on which the API is to act. The default heap in each activation group always has an identifier of 0 (zero).
- The RPG dynamic memory op-codes always operate on the default heap, so no identifier is necessary.
- Heaps are "owned" by the activation group in which they are created. When an activation group ends, all the heaps it owns are discarded.
- A heap's unique identifier is meaningful only within the activation group that owns the heap.
- Programs can manually create and discard additional heaps to satisfy unique storage requirements. User-created heaps can be created using the CEECRHP API and discarded with the CEEDSHP API. However, they can only be accessed using certain APIs.
- Heaps are created with a fixed size. The size is extended automatically to satisfy allocation requests.
- The maximum size for a heap is just under 4 GB provided there are not more than 128,000 individual allocations at a given time. The maximum size decreases in the off-chance the maximum number of allocations is exceeded.
- The maximum number of bytes for any allocation is limited to just under 16 MB.
- Programs in different activation groups can share the same heap. For example, a program can allocate a block of memory off it's default heap, then call another program that runs in a different activation group. If the first program passes a pointer to the allocated heap memory to the second program, the second program has full access to the heap in the activation in which the first program is running. It can access the memory as usual, and it can use the Realloc and Dealloc op-codes against it.