Why does the loop variable address change when it is used?

Program 1:

library(pryr) for (x in 1:3) { print(c(address(x), refs(x))) } 

Output, for example:

 [1] "0x7a6a6c8" "1" [1] "0x7a6a6c8" "1" [1] "0x7a6a6c8" "1" 

Program 2:

 library(pryr) for (x in 1:3) { print(c(address(x), refs(x))) print(x) } 

Output, for example:

 [1] "0x7ae0298" "1" [1] 1 [1] "0x7ae88c8" "1" [1] 2 [1] "0x7af2668" "1" [1] 3 

Obviously, the value of x changes in program 2, but why does the address change? Could this lead to a memory leak if there is a for loop that runs about 500,000,000 times, while gc is not called during the loop?

+7
memory for-loop r pryr
source share
1 answer

After printing (x) at the end of the loop, this is indicated as a multiple link, as mentioned in @alexis_laz. Because R is a dynamic language, this can happen easily. To test the effect of this, we can print the output of ref (x), print (x), refs (x):

 for (x in 1:3) { print(refs(x)) print(x) print(refs(x)); cat("\n") } 

Output:

 [1] 1 [1] 1 [1] 2 [1] 1 [1] 2 [1] 2 [1] 1 [1] 3 [1] 2 
+1
source share

All Articles