Manual memory management
Factor handbook > C library interface > Passing data between Factor and C

Prev:Passing pointers to C functions
Next:C strings

Sometimes data passed to C functions must be allocated at a fixed address. See Byte arrays and the garbage collector for an explanation of when this is the case.

Allocating a C datum with a fixed address:
malloc-byte-array ( byte-array -- alien )

The libc vocabulary defines several words which directly call C standard library memory management functions:
malloc ( size -- alien )

calloc ( count size -- alien )

realloc ( alien size -- newalien )

You must always free pointers returned by any of the above words when the block of memory is no longer in use:
free ( alien -- )

The above words record memory allocations, to help catch double frees and track down memory leaks with Destructor tools. To free memory allocated by a C library, another word can be used:
(free) ( alien -- )

Utilities for automatically freeing memory in conjunction with with-destructors:
&free ( alien -- alien )

|free ( alien -- alien )

The &free and |free words are generated using Alien destructors.

You can unsafely copy a range of bytes from one memory location to another:
memcpy ( dst src size -- )

You can copy a range of bytes from memory into a byte array:
memory>byte-array ( alien len -- byte-array )