User Tools

Site Tools


lowering_himem_proc_fn

Lowering HIMEM in a PROC/FN

by Richard Russell, July 2024

One way of reserving a block of memory is to lower HIMEM, this frees up the region between the new value of HIMEM and the old value of HIMEM (-1), for example to contain assembly language code or for any other purpose. A specific advantage of this method is that the memory region thus reserved is maintained throughout the rest of the 'session', even if new programs are loaded, unless HIMEM is raised again.

Lowering HIMEM is straightforward when done in your 'main program', i.e. not inside a procedure or function (amount% should normally be a multiple of four to maintain stack alignment):

      HIMEM = HIMEM - amount%

However lowering HIMEM within a PROC or FN is not so easy. The code above will appear to work, and indeed if you PRINT HIMEM afterwards it will indicate that it has been changed, but since calling a PROC or FN involves the stack (which grows down from HIMEM) the block of memory between the new and old values of HIMEM is still in use! Loading data of some kind into this region will almost certainly corrupt the stack and result in a serious crash.

To successfully reserve a block of memory, by lowering HIMEM, within a procedure or function is more complicated. It involves copying the contents of the stack from its original location to a new location, so that it no longer occupies the reserved memory region.

The code below can be used to achieve this. Note that the block of reserved memory begins at the (new) value of HIMEM, not at b%​% as the code might superficially suggest:

      DEF PROC_lower_himem(amount%)
      LOCAL b%%, d%%, s%%
      DIM s%% LOCAL TRUE, b%% LOCAL amount%, d%% LOCAL TRUE
      WHILE s%% < HIMEM
        ?d%% = ?s%%
        d%% += 1 : s%% += 1
      ENDWHILE
      HIMEM = d%%
      ENDPROC

This code should be used with great care because moving the stack is not recommended and there are some circumstances when it will not work correctly (for example if a LOCAL array has previously been allocated on the stack). It should be used only when lowering HIMEM in the main program isn't acceptable, for example because you want to do it inside a library function.

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
lowering_himem_proc_fn.txt · Last modified: 2024/07/06 12:40 by richardrussell