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()
          • Compatibility between Prolog versions
          • Foreign hash tables
          • Debugging and profiling foreign code (valgrind, asan)
          • 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.