[Rd] Truncating vectors by reference in C-backend

mbonsch at posteo.de mbonsch at posteo.de
Tue Nov 21 07:36:36 CET 2017


Dear all,

I want to create a function shrinkVector(x) that takes x and truncates 
it to the first element without copy.
With SETLENGTH and SET_TRUELENGTH, I can achieve that.  You can find a 
reproducible example below.
But the memory that was freed is not available for other objects 
afterwards, except if x is a list (VECSXP). Any suggestions?

library(inline)
## define the shrinking function
shrinkVector <- cfunction(signature(x = "ANY"),
                           body = paste0("SETLENGTH(x, 1);",
                                                   "SET_TRUELENGTH(x, 
1);",
                                                   
"return(R_NilValue);"))
## create a large vector that only fits into memory once
x <- 1 : 2e9
## shrink it
shrinkVector(x)
## shrinking seems to have worked
print(length(x) == 1)
# [1] TRUE
print(object.size(x))
# 48 bytes
## but I can't reuse the memory for a large x2:
x2 <- 1 : 2e8
# Error: cannot allocate vector of size 762.9 Mb
## if I remove x, it works
rm(x)
gc()
x2 <- 1 : 2e8

Thank you very much for your help.

Kind regards,
Markus Bonsch



More information about the R-devel mailing list