[Rd] The finalizer of the externalPtr does not work when closing R?

Wang Jiefei @zwj|08 @end|ng |rom gm@||@com
Fri Apr 3 14:55:29 CEST 2020


Hi all,

I found that the finalizer of the externalPtr is not called when R is
quitting. However, manually calling GC() works fine. This behavior is
observed on devel R 2020-04-02 r78142 on Win and R 3.6.3 on Ubuntu.  I make
a reproducible package here: https://github.com/Jiefei-Wang/example

Here is the detail of how to reproduce the problem, I create a temporary
file in the package root path and make an external pointer. The finalizer
of the external pointer will delete the  temporary file when it is called.
In the first round, I manually remove the external pointer from the global
environment and call GC() to verify if the finalizer is programmed
properly. The temporary file is deleted successfully. Then I create the
file and the pointer again and close the R session without saving the
global environment. Since the external pointer is removed when closing R,
so the finalizer should be called in this procedure. However, the temp file
still exists after closing the R session.

Here is the test code(which can be found in inst/example/example.R)

## Create a temporary file
tmpFile <- paste0(system.file(package = "testPackage"), "/tmp")
tmpFile
file.create(tmpFile)
file.exists(tmpFile)
## Create an external pointer whose finalizer will delete
## the file when the variable is not in used
x <- testPackage:::makeExtPtr(file.remove,tmpFile)
## GC is working fine
rm(list="x")
gc()
file.exists(tmpFile)

## Create the temporary file again
file.create(tmpFile)
file.exists(tmpFile)
x <- testPackage:::makeExtPtr(file.remove,tmpFile)
## Quit R session without explicitly cleaning the working space
quit(save = "no")


##=====Open a new R session=======
## The temporary file still exist
tmpFile <- paste0(system.file(package = "testPackage"), "/tmp")
file.exists(tmpFile)

Not sure if this behavior is designed on purpose, but it sounds wired to me
and can cause memory leaking if not properly handled.

Best,
Jiefei

	[[alternative HTML version deleted]]



More information about the R-devel mailing list