BASIC memory usage

From BeebWiki
Jump to: navigation, search


BBC BASIC memory space is arranged as shown in this diagram:

   +-----------+ HIMEM
   |   BASIC   |
   |   stack   |
   +-----------+ STACK        ^
   |   free    |              |
   |   space   |              |
   +-----------+ VARTOP  increasing
   |   heap    |           memory
   |(variables)|          addresses
   +-----------+ LOMEM
   +-----------+ TOP
   |  program  |
   +-----------+ PAGE

PAGE, TOP, LOMEM and HIMEM are pseudo-variables available in all versions of BBC BASIC. The BASIC program expands upwards from PAGE, the variables expand upwards from LOMEM, and the BASIC stack descends downwards from HIMEM. You can write to PAGE, LOMEM and HIMEM to change what memory BASIC uses for the program and the heap (variables). TOP and END cannot be changed as they are the end of a dynamic area.

LOMEM usually defaults to TOP, but it can be moved anywhere. You can even swap around the BASIC program and the heap (variable) space if you are careful (see this article).

Some versions of BASIC also use END to return VARTOP. However, on all versions of BASIC DIM numvar -1 sets numvar to the top of the heap by allocating zero bytes of space and pointing numvar to it.

There is no universal method of reading STACK, the bottom of the BASIC stack. Some versions of BASIC allow you to reserve space on the stack, and DIM numvar LOCAL -1 sets numvar to the bottom of the stack by allocating zero bytes of space and pointing numvar to it. Otherwise, depending on how deeply the program has recursed into multiple PROCs or FNs, 256 bytes is a usable approximation.

Calculating memory sizes

The size of each area of memory used by BASIC can be calculated as follows:

Program size  size%=TOP-PAGE
Total heap size  size%=HIMEM-LOMEM
Used heap size  DIM A% -1:size%=A%-LOMEM
Free heap size  DIM A% -1:size%=HIMEM-A%-256

See also

Jgharston (talk) 16:20, 31 October 2015 (UTC)