You could try {constructive} : https://github.com/cynkra/constructive/
Here's how it might help:
```
E <- new.env()
fun <- function(x) x
environment(fun) <- E
O <- list(
a = 1,
b = fun
)
# remotes::install_github("cynkra/constructive")
library(constructive)
construct(E)
#> constructive::env("0x1075b2380", parents = "global")
construct(O)
#> list(
#> a = 1,
#> b = (function(x) x) |>
#> (`environment<-`)(constructive::env("0x1075b2380",
parents "global"))
#> )
```
By searching for `0x1075b2380` here you'd easily find where it's
referenced.
If you have S4 objects in there you might want to try again in a few days
since they're not supported yet.
If the output is too big consider `construct_dump(list(O = O),
"out.R")`
Thanks,
Antoine
> Message: 1
> Date: Tue, 23 May 2023 11:29:19 -0700
> From: Peter Meilstrup <peter.meilstrup at gmail.com>
> To: r-devel <r-devel at r-project.org>
> Subject: [Rd] How to locate references to an environment?
> Message-ID:
> <CAJoaRhY53Xh5x2WO=zcMwxeRJ2SLo7mN3=_AfiqcoNiAN> Q8sQ at
mail.gmail.com>
> Content-Type: text/plain; charset="utf-8"
>
> R developers,
>
> I am trying to track down a memory leak in my R package.
>
> I have a complex object O which comprises a lot of closures and such.
> Among which, the object uses an environment E to perform computations
> and keep intermediate values in. When O closes/finishes with its task
> it nulls out its reference to E so that that intermediate data can be
> garbage collected; I've verified that it does null the reference.
>
> However, it seems there is another reference to E floating around. I
> can tell because I can ask O to put a large array in E, then tell O to
> close, which nulls the reference to E, but then if I serialize(O,
> ascii=TRUE) I can still see the array in the output.
>
> Dangling references to E could come from a closure created in E, or an
> unforced promise from a function call evaluated in E that created a
> closure I still have a reference to, or, ... my question is how do I
> locate the reference?
>
> Is there a way to scan the workspace for objects that refer to a given
> object?
>
> Or is there a tool that will unpack/explain serialize()'s .rds format
> in a more human-readable way so that I can tell where the reference to
> E occurs?
>
> Peter
>
>
>
[[alternative HTML version deleted]]