[Rd] Memory "leak" in readChar (PR#1483)

hcp@met.ed.ac.uk hcp@met.ed.ac.uk
Fri, 26 Apr 2002 11:05:55 +0200 (MET DST)

Full_Name: Hugh C. Pumphrey
Version: 1.4.1
OS: Linux (Debian Woody)
Submission from: (NULL) (

The function readChar() appears to have some type of problem with memory
I don't know if "memory leak" is the correct term but if one uses readChar()
times, the R binary grows in size until it eats all your memory and swap space.

The code enclosed below demonstrates the problem. As-is, it causes the size
of R.bin to grow from 11MB to 50MB, even though there are no large arrays. 
The old Rstreams package did not do this. Also, the function readBin() does
not suffer from this problem.

## Stress read/write of files in binary mode to see if there is a memory leak
## Now, readBin seems to be innocent. The memory leak is in readChar
header <-paste("This is a very long and boring text header which appears",
               "at the beginning of each chunk of an even longer and duller",
               "file which contains mostly binary data")
nchars <- nchar(header)
nrecs <-2000
ntries <- 100

## Write a test file
stream <- file("/tmp/gunge")
for(irec in 1:nrecs){
  ## This writes null-ended strings unless you use the eos=NULL option

## Read in the file ntries times. In real applications one would be reading
## ntries _different_ files and calculating some summary statistics 
for(itry in 1:ntries){
  stream <- file("/tmp/gunge")
  if(itry %% 10== 0) print(itry)
  for(irec in 1:nrecs){
    iheader <- readChar(stream,nchars)

r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch