MainframeMaster
MainframeMaster

COBOL Tutorial

Progress0 of 0 lessons

COBOL Dynamic Memory

Dynamic memory allocation in COBOL allows programs to allocate and free memory at runtime rather than having all memory pre-allocated at compile time. This enables more efficient memory usage, handling of variable-sized data structures, and memory management based on runtime conditions. COBOL provides the ALLOCATE and FREE statements, along with pointers and BASED storage, to support dynamic memory management.

This comprehensive guide will teach you how to use ALLOCATE to dynamically allocate memory, FREE to release it, work with pointers to reference allocated memory, use BASED storage for dynamic structures, and follow best practices for efficient memory management. Understanding dynamic memory is essential for modern COBOL programming, especially when dealing with variable-length data, dynamic arrays, and memory-efficient processing.

What is Dynamic Memory?

Dynamic memory is memory that is allocated and freed at runtime, as opposed to static memory which is allocated at compile time. Dynamic memory provides:

  • Flexibility: Allocate memory only when needed, based on runtime conditions
  • Efficiency: Use memory only for the amount needed, not a fixed maximum
  • Variable sizing: Handle data structures of varying sizes
  • Conditional allocation: Allocate memory based on program logic and conditions

COBOL supports dynamic memory through:

  • ALLOCATE statement: Dynamically allocates memory for data items
  • FREE statement: Releases dynamically allocated memory
  • Pointers: Reference dynamically allocated memory
  • BASED storage: Data items stored at locations specified by pointers

Static vs Dynamic Memory

Understanding the difference between static and dynamic memory:

Static vs Dynamic Memory Comparison
AspectStatic MemoryDynamic Memory
Allocation TimeCompile time (when program is compiled)Runtime (when ALLOCATE executes)
SizeFixed size determined at compile timeVariable size determined at runtime
LocationFixed location in memoryLocation determined at runtime
LifetimeEntire program executionFrom ALLOCATE until FREE
ManagementAutomatic, no explicit management neededExplicit ALLOCATE and FREE required
Use CasesFixed-size, always-needed dataVariable-size or conditionally-needed data
ExampleWORKING-STORAGE data itemsALLOCATE ... RETURNING pointer

Pointers

Pointers in COBOL are data items that contain memory addresses. They're used to reference dynamically allocated memory. Pointers are defined with USAGE IS POINTER.

Defining Pointers

cobol
1
2
3
4
WORKING-STORAGE SECTION. 01 RECORD-POINTER USAGE IS POINTER. 01 DATA-POINTER USAGE IS POINTER. 01 NULL-POINTER USAGE IS POINTER VALUE NULL.

Pointer characteristics:

  • USAGE IS POINTER: Defines a data item as a pointer
  • Contains addresses: Stores memory addresses, not data values
  • NULL value: Can be initialized to NULL to indicate no memory is referenced
  • Used with ALLOCATE: ALLOCATE can return a pointer to allocated memory
  • Used with BASED: BASED data items are accessed through pointers

ALLOCATE Statement

The ALLOCATE statement dynamically allocates memory for data items at runtime.

ALLOCATE Syntax

cobol
1
ALLOCATE identifier-1 [INITIALIZED] [RETURNING pointer-name]

Components:

  • identifier-1: The data item for which memory is allocated
  • INITIALIZED: Optional. Initializes allocated memory to initial values
  • RETURNING pointer-name: Optional. Returns a pointer to the allocated memory

Basic ALLOCATE Example

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
WORKING-STORAGE SECTION. 01 DYNAMIC-RECORD. 05 CUSTOMER-ID PIC 9(8). 05 CUSTOMER-NAME PIC X(30). 05 ACCOUNT-BALANCE PIC 9(8)V99. 01 RECORD-PTR USAGE IS POINTER. PROCEDURE DIVISION. MAIN-LOGIC. *> Allocate memory for dynamic record ALLOCATE DYNAMIC-RECORD RETURNING RECORD-PTR *> Use allocated memory through pointer SET ADDRESS OF DYNAMIC-RECORD TO RECORD-PTR MOVE 12345678 TO CUSTOMER-ID MOVE 'JOHN SMITH' TO CUSTOMER-NAME MOVE 1000.00 TO ACCOUNT-BALANCE DISPLAY "Customer ID: " CUSTOMER-ID DISPLAY "Customer Name: " CUSTOMER-NAME DISPLAY "Balance: $" ACCOUNT-BALANCE *> Free allocated memory FREE RECORD-PTR STOP RUN.

This example allocates memory for a record, uses it, and then frees it. The pointer is used to reference the allocated memory.

ALLOCATE with INITIALIZED

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
WORKING-STORAGE SECTION. 01 INITIALIZED-RECORD. 05 FIELD-1 PIC 9(5) VALUE 0. 05 FIELD-2 PIC X(10) VALUE SPACES. 01 RECORD-PTR USAGE IS POINTER. PROCEDURE DIVISION. MAIN-LOGIC. *> Allocate and initialize memory ALLOCATE INITIALIZED-RECORD RETURNING RECORD-PTR *> Memory is initialized to VALUE clauses SET ADDRESS OF INITIALIZED-RECORD TO RECORD-PTR DISPLAY "Field 1: " FIELD-1 *> Displays 0 DISPLAY "Field 2: [" FIELD-2 "]" *> Displays spaces FREE RECORD-PTR STOP RUN.

INITIALIZED causes the allocated memory to be initialized to the values specified in VALUE clauses.

FREE Statement

The FREE statement releases dynamically allocated memory back to the system.

FREE Syntax

cobol
1
FREE pointer-name [identifier]

Components:

  • pointer-name: Pointer to the memory to be freed
  • identifier: Optional. Alternative way to specify memory to free

FREE Example

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
WORKING-STORAGE SECTION. 01 DYNAMIC-DATA PIC X(100). 01 DATA-PTR USAGE IS POINTER. PROCEDURE DIVISION. MAIN-LOGIC. *> Allocate memory ALLOCATE DYNAMIC-DATA RETURNING DATA-PTR *> Use allocated memory SET ADDRESS OF DYNAMIC-DATA TO DATA-PTR MOVE "Hello, World!" TO DYNAMIC-DATA DISPLAY DYNAMIC-DATA *> Free allocated memory FREE DATA-PTR *> After FREE, the memory is no longer accessible *> Attempting to use DATA-PTR is undefined STOP RUN.

Always FREE allocated memory when it's no longer needed to prevent memory leaks. After FREE, the memory is no longer accessible through the pointer.

BASED Storage

BASED storage allows data items to be stored at a location specified by a pointer rather than at a fixed location. BASED data items are accessed through their associated pointer.

Defining BASED Data Items

cobol
1
2
3
4
5
6
WORKING-STORAGE SECTION. 01 BASE-POINTER USAGE IS POINTER. 01 BASED-RECORD BASED. 05 RECORD-ID PIC 9(8). 05 RECORD-NAME PIC X(30). 05 RECORD-VALUE PIC 9(8)V99.

BASED characteristics:

  • BASED clause: Indicates the data item is stored at a pointer location
  • No fixed location: Storage location is determined by a pointer
  • Accessed through pointer: Use SET to associate pointer with BASED item
  • Dynamic sizing: Enables variable-sized structures

Using BASED Storage

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
WORKING-STORAGE SECTION. 01 RECORD-PTR USAGE IS POINTER. 01 DYNAMIC-RECORD BASED. 05 CUSTOMER-ID PIC 9(8). 05 CUSTOMER-NAME PIC X(30). 05 ACCOUNT-BALANCE PIC 9(8)V99. PROCEDURE DIVISION. MAIN-LOGIC. *> Allocate memory ALLOCATE DYNAMIC-RECORD RETURNING RECORD-PTR *> Set pointer to access BASED record SET ADDRESS OF DYNAMIC-RECORD TO RECORD-PTR *> Use BASED record MOVE 12345678 TO CUSTOMER-ID MOVE 'JOHN SMITH' TO CUSTOMER-NAME MOVE 1000.00 TO ACCOUNT-BALANCE DISPLAY "ID: " CUSTOMER-ID DISPLAY "Name: " CUSTOMER-NAME DISPLAY "Balance: $" ACCOUNT-BALANCE *> Free memory FREE RECORD-PTR STOP RUN.

BASED storage allows the same data structure to be used with different memory locations, enabling dynamic memory management.

Complete Dynamic Memory Example

Here's a complete example demonstrating dynamic memory allocation and management:

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
IDENTIFICATION DIVISION. PROGRAM-ID. DYNAMIC-MEMORY-EXAMPLE. AUTHOR. MainframeMaster Tutorial. REMARKS. Complete example demonstrating dynamic memory allocation. DATA DIVISION. WORKING-STORAGE SECTION. 01 CUSTOMER-PTR USAGE IS POINTER VALUE NULL. 01 CUSTOMER-COUNT PIC 9(4) VALUE 0. 01 ALLOCATION-FLAG PIC X(1) VALUE 'N'. 88 MEMORY-ALLOCATED VALUE 'Y'. 88 MEMORY-NOT-ALLOCATED VALUE 'N'. 01 CUSTOMER-RECORD BASED. 05 CUST-ID PIC 9(8). 05 CUST-NAME PIC X(30). 05 CUST-BALANCE PIC 9(8)V99. 05 CUST-STATUS PIC X(1). PROCEDURE DIVISION. MAIN-LOGIC. DISPLAY "=== Dynamic Memory Management Example ===" DISPLAY " " PERFORM ALLOCATE-CUSTOMER-RECORD IF MEMORY-ALLOCATED PERFORM POPULATE-CUSTOMER-DATA PERFORM DISPLAY-CUSTOMER-DATA PERFORM FREE-CUSTOMER-RECORD END-IF DISPLAY " " DISPLAY "Dynamic memory example completed" STOP RUN. ALLOCATE-CUSTOMER-RECORD. DISPLAY "Allocating memory for customer record..." *> Allocate memory with initialization ALLOCATE INITIALIZED CUSTOMER-RECORD RETURNING CUSTOMER-PTR IF CUSTOMER-PTR NOT = NULL MOVE 'Y' TO ALLOCATION-FLAG SET ADDRESS OF CUSTOMER-RECORD TO CUSTOMER-PTR DISPLAY "Memory allocated successfully" ELSE DISPLAY "ERROR: Memory allocation failed" MOVE 'N' TO ALLOCATION-FLAG END-IF. POPULATE-CUSTOMER-DATA. DISPLAY "Populating customer data..." MOVE 12345678 TO CUST-ID MOVE 'JOHN SMITH' TO CUST-NAME MOVE 5000.00 TO CUST-BALANCE MOVE 'A' TO CUST-STATUS DISPLAY "Customer data populated". DISPLAY-CUSTOMER-DATA. DISPLAY " " DISPLAY "Customer Information:" DISPLAY " ID: " CUST-ID DISPLAY " Name: " CUST-NAME DISPLAY " Balance: $" CUST-BALANCE DISPLAY " Status: " CUST-STATUS. FREE-CUSTOMER-RECORD. DISPLAY " " DISPLAY "Freeing allocated memory..." IF CUSTOMER-PTR NOT = NULL FREE CUSTOMER-PTR MOVE NULL TO CUSTOMER-PTR MOVE 'N' TO ALLOCATION-FLAG DISPLAY "Memory freed successfully" ELSE DISPLAY "WARNING: Attempting to free NULL pointer" END-IF.

This complete example demonstrates allocating memory, using it, and freeing it. It includes error checking and proper memory management practices.

Memory Leaks and Best Practices

Memory leaks occur when dynamically allocated memory is not freed, causing memory to be unavailable for reuse. Follow these best practices to prevent memory leaks and manage memory efficiently:

  • Always pair ALLOCATE with FREE: For every ALLOCATE, ensure there's a corresponding FREE
  • Initialize pointers to NULL: Set pointers to NULL before use and after FREE
  • Check allocation success: Verify that ALLOCATE succeeded before using memory
  • FREE in same scope: When possible, FREE memory in the same scope where it was allocated
  • Don't access freed memory: Never access memory after it has been freed
  • Use meaningful pointer names: Name pointers clearly to indicate their purpose
  • Document allocation patterns: Comment code to explain memory allocation and deallocation
  • Handle allocation failures: Check for NULL pointers and handle allocation failures gracefully
  • Test with various scenarios: Test memory allocation with different data sizes and conditions
  • Consider memory limits: Be aware of system memory limits and allocation constraints

Common Dynamic Memory Patterns

Pattern 1: Allocate, Use, Free

cobol
1
2
3
4
5
ALLOCATE DATA-ITEM RETURNING DATA-PTR *> Use allocated memory SET ADDRESS OF DATA-ITEM TO DATA-PTR *> ... use DATA-ITEM ... FREE DATA-PTR

Pattern 2: Conditional Allocation

cobol
1
2
3
4
5
6
7
IF CONDITION-MET ALLOCATE DATA-ITEM RETURNING DATA-PTR *> Use allocated memory SET ADDRESS OF DATA-ITEM TO DATA-PTR *> ... process ... FREE DATA-PTR END-IF

Pattern 3: Multiple Allocations

cobol
1
2
3
4
5
6
ALLOCATE RECORD-1 RETURNING PTR-1 ALLOCATE RECORD-2 RETURNING PTR-2 *> Use both records *> ... process ... FREE PTR-1 FREE PTR-2

Pattern 4: BASED Storage with Pointer

cobol
1
2
3
4
5
ALLOCATE BASED-RECORD RETURNING RECORD-PTR SET ADDRESS OF BASED-RECORD TO RECORD-PTR *> Use BASED-RECORD *> ... process ... FREE RECORD-PTR

Explain Like I'm 5: Dynamic Memory

Think of dynamic memory like borrowing books from a library:

  • ALLOCATE is like checking out a book - you get it when you need it
  • FREE is like returning the book - you give it back when you're done
  • Pointer is like a library card that tells you where your book is
  • BASED storage is like having a bookmark that points to a specific page
  • Memory leak is like forgetting to return a book - it stays checked out and others can't use it

So dynamic memory is like a library system for your program - you get memory when you need it, use it, and return it when you're done!

Practice Exercises

Complete these exercises to reinforce your understanding:

Exercise 1: Basic Allocation

Create a program that allocates memory for a customer record, populates it with data, displays it, and then frees the memory.

Exercise 2: Conditional Allocation

Create a program that conditionally allocates memory based on user input. If the user enters "Y", allocate and use memory; if "N", skip allocation. Always free memory if it was allocated.

Exercise 3: Multiple Allocations

Create a program that allocates memory for three different records, populates them, displays them, and frees all three allocations.

Exercise 4: BASED Storage

Create a program that uses BASED storage with a pointer. Allocate memory, set the pointer, use the BASED record, and free the memory.

Exercise 5: Error Handling

Create a program that allocates memory, checks for successful allocation, handles allocation failures gracefully, and ensures memory is freed even if errors occur.

Test Your Knowledge

1. What statement is used to dynamically allocate memory in COBOL?

  • MOVE
  • ALLOCATE
  • SET
  • ASSIGN

2. What statement is used to release dynamically allocated memory?

  • RELEASE
  • FREE
  • DEALLOCATE
  • CLEAR

3. What is a pointer in COBOL?

  • A data item that contains a memory address
  • A data item that points to a file
  • A data item that contains a value
  • A data item that contains a record

4. What is BASED storage in COBOL?

  • Storage allocated at compile time
  • Storage stored at a location specified by a pointer
  • Storage in a file
  • Storage in working storage

5. What happens if you don't FREE allocated memory?

  • Nothing, memory is automatically freed
  • Memory leak - memory becomes unavailable
  • Program crashes immediately
  • Memory is freed at program end

6. How do you access dynamically allocated memory?

  • Directly by name
  • Through a pointer
  • Through a file
  • Through working storage

7. What is the difference between static and dynamic memory?

  • There is no difference
  • Static is allocated at compile time, dynamic at runtime
  • Static is faster, dynamic is slower
  • Static uses pointers, dynamic doesn't

8. When should you use dynamic memory allocation?

  • Always, for all data
  • Never, use static memory only
  • For variable-size or conditionally-needed data
  • Only for file operations

Related Concepts

Related Pages