[R] main/character.c (et.al): dangerous AllocBuffer()

Thomas Hoffmann hoffmann at ehmgs2.et.tu-dresden.de
Wed Oct 13 15:21:11 CEST 1999


I was hit by ugly crashes of R, when I tried to read big data sets ("volcano").
So I looked into the code and found the following in character.c (triggered by substr()):

I assume that the helper function AllocBuffer() shall facilitate an economic memory management. But 
the use of realloc() in the else-branch does not conform to ANSI and may hit you with certain 
compilers.

When called with len<0 the code is assumed to re-size buff to MAXELTSIZE:

	realloc(buff, 0);
	buff = (char *) realloc(buff, MAXELTSIZE);
	bufsize = MAXELTSIZE;
	
But in the first call of realloc() it is perfectly legal to return a new pointer (which is thrown away 
here), and then using (a possibly invalid) buff from earlier times may (and did for me) crash your 
program.

Why not use 
	free(buff);
	buff = malloc(MAXELTSIZE);
	bufsize = MAXELTSIZE;
instead? (Or just free(buff); bufsize=0;, you will malloc() the next
round, then).

Most of the UNIX compilers seem to keep the address of buff, so that you get away with this.

BTW, a check for failing [re,m]alloc may be appropriate.
 		 
I hope this list is the right one for comments of this kind.

Regards,
Thomas. 		 
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help 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-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list