Code: Select all
DIM memory%% size%
Code: Select all
DIM memory%% LOCAL size%
Although these two options will satisfy most memory allocation requirements, sometimes they may be too limiting. If you want to be able to allocate and free memory blocks without the constraints they impose, one option is to call an Operating System API function to do so. For example in BBC BASIC for Windows you can allocate memory using SYS "GlobalAlloc" and free it again using SYS "GlobalFree". Similarly in BBC BASIC for SDL 2.0 you can allocate memory using SYS "SDL_malloc" and free it with SYS "SDL_free".
But, when the amounts of memory you want to allocate are relatively small, there is an alternative approach that does not require API calls and works in both BB4W and BBCSDL. BBC BASIC already has a reasonably sophisticated dynamic memory management mechanism which it uses for strings, so the trick is to leverage this by allocating the memory block in a string! It turns out that this is relatively straightforward, as the function and procedure listed below demonstrate:
Code: Select all
DEF FN_heapalloc(N%)
LOCAL a$, p%%
a$ = STRING$(N% + 23, CHR$0)
p%% = PTR(a$) + 23 AND -16
SWAP ](p%%-8), ]^a$
= p%%
Code: Select all
DEF PROC_heapfree(p%%)
LOCAL a$
SWAP ]^a$, ](p%%-8)
a$ = ""
ENDPROC
These routines may not be as efficient or fast as the OS equivalents, and they use up space in BASIC's heap which the OS allocation functions don't, but nevertheless there may be occasions when they are useful.