### 14.1 How Overlays Work

Suppose you have a computer whose instruction address space is only 64 kilobytes long, but which has much more memory which can be accessed by other means: special instructions, segment registers, or memory management hardware, for example. Suppose further that you want to adapt a program which is larger than 64 kilobytes to run on this system.

One solution is to identify modules of your program which are relatively independent, and need not call each other directly; call these modules overlays. Separate the overlays from the main program, and place their machine code in the larger memory. Place your main program in instruction memory, but leave at least enough space there to hold the largest overlay as well.

Now, to call a function located in an overlay, you must first copy that overlay’s machine code from the large memory into the space set aside for it in the instruction memory, and then jump to its entry point there.

```    Data             Instruction            Larger
+-----------+       +-----------+        +-----------+
|           |       |           |        |           |
+-----------+       +-----------+        +-----------+<-- overlay 1
| program   |       |   main    |   .----| overlay 1 | load address
| variables |       |  program  |   |    +-----------+
| and heap  |       |           |   |    |           |
+-----------+       |           |   |    +-----------+<-- overlay 2
+-----------+       |           |   |  .-| overlay 2 |
|           |   |  | |           |
mapped --->+-----------+   |  | +-----------+
address    |           |   |  | |           |
|  overlay  | <-'  | |           |
|   area    |  <---' +-----------+<-- overlay 3
+-----------+     `--| overlay 3 |
|           |        |           |
+-----------+        |           |
+-----------+
|           |
+-----------+

A code overlay```

The diagram (see A code overlay) shows a system with separate data and instruction address spaces. To map an overlay, the program copies its code from the larger address space to the instruction address space. Since the overlays shown here all use the same mapped address, only one may be mapped at a time. For a system with a single address space for data and instructions, the diagram would be similar, except that the program variables and heap would share an address space with the main program and the overlay area.