BudiBadu Logo
Samplebadu

COBOL by Example: Pointer Data

COBOL 2002

Managing dynamic memory with POINTER data type for heap allocation, using ALLOCATE statement to request memory, implementing BASED clause for template variables without fixed storage, mapping memory addresses with SET ADDRESS OF, and preventing leaks with explicit FREE statement.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. PTR-DEMO.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  MY-PTR      USAGE POINTER.
       01  VAL-AREA    PIC X(10) BASED.
       
       PROCEDURE DIVISION.
           ALLOCATE 10 CHARACTERS RETURNING MY-PTR.
           SET ADDRESS OF VAL-AREA TO MY-PTR.
           
           MOVE "Dynamic" TO VAL-AREA.
           DISPLAY "Content: " VAL-AREA.
           
           FREE MY-PTR.
           STOP RUN.

Explanation

While COBOL is traditionally a static language, modern standards support POINTER data types for dynamic memory management. This is essential when interfacing with C APIs, handling large buffers, or when the amount of data isn't known at compile time.

The BASED clause (or LINKAGE SECTION in older dialects) declares a variable that doesn't have its own memory. Instead, it acts as a template or "mask" that you can overlay onto any memory address. You use SET ADDRESS OF to point this template to a memory block allocated via ALLOCATE.

Manual memory management comes with responsibilities. You must explicitly FREE any memory you allocate to prevent memory leaks. This is a departure from the safe, static world of traditional COBOL but offers necessary power for system-level programming.

Code Breakdown

6
USAGE POINTER. Declares a variable that holds a memory address (4 or 8 bytes), not data.
7
BASED. Tells the compiler this variable is a template. It has no physical storage until we assign it an address.
10
ALLOCATE 10 CHARACTERS. Requests 10 bytes of memory from the heap.
10
RETURNING MY-PTR. Stores the address of the newly allocated memory into our pointer variable.
11
SET ADDRESS OF ... TO. Maps the BASED variable VAL-AREA to the memory address held in MY-PTR. Now, VAL-AREA refers to those 10 bytes.
13
MOVE "Dynamic" TO VAL-AREA. We can now use VAL-AREA like any normal variable.
16
FREE MY-PTR. Releases the memory back to the system. Accessing VAL-AREA after this would cause a crash.