10 important things to remember about heaps
Using dynamic memory and theAlloc, Dealloc, and Realloc built-in functions and op-codes is pretty straight-forward once you understand the following 10 things about heaps:
1. First and foremost, a heap is tied to – or scoped to – the activation group in which it was created. Each activation group has at least 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 (you can find more information about user-created heaps in the System API Reference manual -- look in the "ILE CEE API" section).
2. Each heap has an identifier. Since there can be multiple heaps in an activation group (i.e., the one default heap plus any user-created heaps), heaps have an ID number in order to uniquely identify them. Many of the 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).
3. The RPG dynamic memory built-in functions and op-codes always operate on the default heap, so no identifier is necessary.
4. Heaps are "owned" by the activation group in which they are created. When an activation group ends, all the heaps it owns are discarded.
5. A heap's unique identifier is meaningful only within the activation group that owns the heap.
6. 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. They can be accessed using the heap APIs previously mentioned.
7. Heaps are created with a fixed size. The system will automatically extend the size if necessary to satisfy allocation requests.
8. 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 number of allocations exceeds 128,000.
9. The maximum number of bytes for any single allocation is limited to just under 16 MB.
10. Programs in different activation groups can share the same heap. For example, a program can allocate a block of memory off its 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 even use the Realloc and Dealloc built-in functions and op-codes against it. However, the called program cannot allocate new blocks out of the calling program's activation group's heap.
About the author: Ron Turull is editor of Inside Version 5. He has more than 20 years' experience programming for and managing AS/400-iSeries systems.
This was first published in August 2006