% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/TMB.R
\name{FreeADFun}
\alias{FreeADFun}
\title{Free memory allocated on the C++ side by \code{MakeADFun}.}
\usage{
FreeADFun(obj)
}
\arguments{
\item{obj}{Object returned by \code{MakeADFun}}
}
\description{
Free memory allocated on the C++ side by \code{MakeADFun}.
}
\details{
An object returned by \code{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
\code{FreeADFun(obj)} to release the resources.
}
\note{
This function is normally not needed.
}
\section{Memory management}{

Memory allocated on the C++ side by \code{MakeADFun} is
represented by external pointers. Each such pointer has an
associated 'finalizer' (see \code{reg.finalizer}) that deallocates
the external pointer when \code{gc()} decides the pointer is no
longer needed.  Deallocated pointers are recognized on the R
side as external null pointers \code{<pointer: (nil)>}. This is
important as it provides a way to prevent the finalizers from
freeing pointers that have already been deallocated \emph{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:
\itemize{
  \item Garbage collection of an external pointer that is no longer needed (triggers corresponding finalizer).
  \item Explicit deallocation of external pointers using \code{FreeADFun()} (corresponding finalizers are untriggered but harmless).
  \item Unload/reload of the user's DLL deallocates all external pointers (corresponding finalizers are untriggered but harmless).
}
}

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