12.8 Notes on Using Foreign Code
AllApplicationManualNameSummaryHelp

  • Documentation
    • Reference manual
      • Foreign Language Interface
        • Notes on Using Foreign Code
          • Foreign debugging functions
          • Memory Allocation
            • PL_malloc()
            • PL_realloc()
            • PL_free()
            • Boehm-GC support
          • Compatibility between Prolog versions
          • Debugging and profiling foreign code (valgrind)
          • Name Conflicts in C modules
          • Compatibility of the Foreign Interface
    • Packages

12.8.2 Memory Allocation

SWI-Prolog's heap memory allocation is based on the malloc(3) library routines. SWI-Prolog provides the functions below as a wrapper around malloc(). Allocation errors in these functions trap SWI-Prolog's fatal-error handler, in which case PL_malloc() or PL_realloc() do not return.

Portable applications must use PL_free() to release strings returned by PL_get_chars() using the BUF_MALLOC argument. Portable applications may use both PL_malloc() and friends or malloc() and friends but should not mix these two sets of functions on the same memory.

void * PL_malloc(size_t bytes)
Allocate bytes of memory. On failure SWI-Prolog's fatal-error handler is called and PL_malloc() does not return. Memory allocated using these functions must use PL_realloc() and PL_free() rather than realloc() and free().
void * PL_realloc(void *mem, size_t size)
Change the size of the allocated chunk, possibly moving it. The mem argument must be obtained from a previous PL_malloc() or PL_realloc() call.
void PL_free(void *mem)
Release memory. The mem argument must be obtained from a previous PL_malloc() or PL_realloc() call.

12.8.2.1 Boehm-GC support

This section is obsolete. Although the Boehm-GC interfaces still exist, it turns out that the scalability is not good enough for SWI-Prolog. It is unlikely that SWI-Prolog will ever switch to Boehm-GC.

To accommodate future use of the Boehm garbage collector186http://www.hpl.hp.com/personal/Hans_Boehm/gc/ for heap memory allocation, the interface provides the functions described below. Foreign extensions that wish to use the Boehm-GC facilities can use these wrappers. Please note that if SWI-Prolog is not compiled to use Boehm-GC (default), the user is responsible for calling PL_free() to reclaim memory.

void* PL_malloc_atomic(size_t bytes)
void* PL_malloc_uncollectable(size_t bytes)
void* PL_malloc_atomic_uncollectable(size_t bytes)
If Boehm-GC is not used, these are all the same as PL_malloc(). With Boehm-GC, these map to the corresponding Boehm-GC functions. Atomic means that the content should not be scanned for pointers, and uncollectable means that the object should never be garbage collected.
void* PL_malloc_stubborn(size_t bytes)
void PL_end_stubborn_change(void *memory)
These functions allow creating objects, promising GC that the content will not change after PL_end_stubborn_change().