Expand/Shrink

allocate

Definition: atom pMem = allocate(integer i, bool cleanup=false)
-- or --
atom pMem = allocate_word(atom v=0, bool cleanup=false, integer size=machine_word())
Description: Allocate i or size bytes of memory and return the address, or 0 (aka NULL) on failure.
The address returned is always machine_word aligned.
pwa/p2js: Not supported.
Comments: If the optional cleanup flag is true (/non-zero), the memory will be automatically released once it is no longer required, otherwise the application should invoke free() manually. Note that you should avoid invoking free() or delete() on pMem when cleanup is true - if nothing else that would explictly invalidate the implicit safety guarantees it provided, and in some cases open the door to unpredictable memory corruption, should there still be a reference to some memory that you have just explicitly said (by invoking said) can now be used for something else (and o/c that whole tribe of potential problems is ever-present when cleanup is false).

In an ideal world the cleanup flag should probably default to true, however that causes far too many problems with legacy code.
(Somewhere beneath the calm waters of the lake my little feet are paddling away furiously...)

The allocate_word() function allocates a single block of size bytes of memory (must be 1/2/4/8) and sets it to (machine integer) v.
Obviously v is defined as atom to allow full 32/64 bit values outside the usual 31/63 bit range, and the same caveats apply as explained in detail in peek() and poke() when using a size of 8 on a 32-bit architecture. The peekns/peeknu/poken() routines are natural companions to allocate_word().
Example:
buffer = allocate(100)
-- (mem_set(buffer,0,100) could be used instead of the following)
for i=0 to 99 do
    poke(buffer+i, 0)
end for
Implementation: Partly in builtins\pAlloc.e (an autoinclude), but mainly via :%pAlloc in builtins\VM\pHeap.e (also an autoinclude) - be warned however it is low-level complicated stuff that you do not need to know.
See Also: free, mem_set, peek, poke, call, delete_routine
Expand/Shrink