IBM AS/400 Frozen Dessert Maker User Manual


 
Managing Dynamically-Allocated Storage
*-----------------------------------------------------------------*
* Heap Storage Misuse *
*-----------------------------------------------------------------*
D Fld1 S 25A BASED(Ptr1)
D Fld2 S 5A BASED(Ptr2)
D Ptr1 S *
D Ptr2 S *
....
C ALLOC 25 Ptr1
C DEALLOC Ptr1
*-----------------------------------------------------------------*
* After this point, Fld1 should not be accessed since the
* basing pointer ptr1 no longer points to allocated storage.
*-----------------------------------------------------------------*
C CALL 'SOMEPGM'
*-----------------------------------------------------------------*
* During the previous call to 'SOMEPGM', several storage
* allocations may have been done.
* In any case, it is extremely dangerous to make the
* following assignment, since 25 bytes of storage will be
* filled with 'a'. It is impossible to know what that storage
* is currently being used for.
*-----------------------------------------------------------------*
C EVAL Fld1 = *ALL'a'
Figure 53. Heap Storage Misuse
Similarly, errors can occur in the following cases:
A similar error can be made if a pointer is copied before being reallocated or
deallocated. Great care must be taken when copying pointers to allocated
storage, to ensure that they are not used after the storage is deallocated or
reallocated.
If a pointer to heap storage is copied, the copy can be used to deallocate or
reallocate the storage. In this case, the original pointer should not be used until
it is set to a new value.
If a pointer to heap storage is passed as a parameter, the callee could deallo-
cate or reallocate the storage. After the call returns, attempts to access the
pointer could cause problems.
If a pointer to heap storage is set in the *INZSR, a later RESET of the pointer
could cause the pointer to get set to storage that is no longer allocated.
Another type of problem can be caused if a pointer to heap storage is lost (by
being cleared, or set to a new pointer by an ALLOC operation, for example).
Once the pointer is lost, the storage it pointed to cannot be freed. This storage
is unavailable to be allocated since the system does not know that the storage
is no longer addressable.
The storage will not be freed until the activation group ends.
Managing Your Own Heap Using ILE Bindable APIs
You can isolate the dynamic storage used by some programs and procedures
within an activation group by creating one or more user-created heaps. For informa-
tion on creating a user-created heap refer to
ILE Concepts
.
The following example shows you how to manage dynamic storage for a run-time
array with a user-created heap from an ILE RPG procedure. In this example, the
Chapter 9. Running a Program 119