FreeADFun: Free memory allocated on the C++ side by 'MakeADFun'.

View source: R/TMB.R

FreeADFunR Documentation

Free memory allocated on the C++ side by MakeADFun.


Free memory allocated on the C++ side by MakeADFun.





Object returned by MakeADFun


An object returned by MakeADFun contains pointers to structures allocated on the C++ side. These are managed by R's garbage collector which for the most cases is sufficient. However, because the garbage collector is unaware of the C++ object sizes, it may fail to release memory to the system as frequently as necessary. In such cases one can manually call FreeADFun(obj) to release the resources.

Memory management

Memory allocated on the C++ side by MakeADFun is represented by external pointers. Each such pointer has an associated 'finalizer' (see reg.finalizer) that deallocates the external pointer when gc() decides the pointer is no longer needed. Deallocated pointers are recognized on the R side as external null pointers <pointer: (nil)>. This is important as it provides a way to prevent the finalizers from freeing pointers that have already been deallocated even if the deallocation C-code has been unloaded. The user DLL maintains a list of all external pointers on the C side. Three events can reduce the list:

  • Garbage collection of an external pointer that is no longer needed (triggers corresponding finalizer).

  • Explicit deallocation of external pointers using FreeADFun() (corresponding finalizers are untriggered but harmless).

  • Unload/reload of the user's DLL deallocates all external pointers (corresponding finalizers are untriggered but harmless).


This function is normally not needed.


runExample("simple", thisR = TRUE)          ## Create 'obj'
FreeADFun(obj)                              ## Free external pointers
obj$fn()                                    ## Re-allocate external pointers

TMB documentation built on Nov. 27, 2023, 5:12 p.m.

Related to FreeADFun in TMB...