Adam Waldemar Kowalewski wrote:
Hello,
I've been writing a program in C that will be called by R. I seem to have
stumbled upon an odd error that seems to suggest there is a limit on the
number of times "Realloc" (the R version as defined in the manual
"R-extenstions" not the C version "realloc") when I try to use the
following program:
#include <R.h>
#include <Rinternals.h>
SEXP test_mem_alloc(SEXP z) {
double *t = Calloc(sizeof(double), double);
*t = 2;
SEXP end_product;
int i = 0;
for(i=1; i < 20; i++) {
t = Realloc(t, sizeof(t) + sizeof(double), double);
The second argument to Realloc is supposed to be the number of elements
to allocate. sizeof(t) is 4 or 8 (32 bit or 64 bit), sizeof double is
8, so you always allocate 12 or 16 elements. Then in the next line you
write out of bounds.
Duncan Murdoch
t[i] = i;
}
PROTECT(end_product = allocVector(REALSXP,6));
for(i = 0; i < 20; i++) {
REAL(end_product)[i] = t[i];
}
UNPROTECT(1);
Free(t);
return end_product;
}
I call it from R using the following script:
z <- 1
test_mem_alloc <- function(z) {
if(!(is.loaded("test_mem_alloc_v6"))) dyn.load("test_mem_alloc_v6.dll")
out <- .Call("test_mem_alloc",
as.double(z))
return(out)
dyn.unload("test_mem_alloc_v6.dll")
}
Basically I get the following error messages:
First:
"Runtime Error!
Program: C:\Program Files\R\R-2.10.0\bin\Rgui.exe
This application has requested the Runtime to terminate it in an unusual
way. Please contact the application's support team for more information."
The second error message is:
"The instruction at "0x0000002c". The memory could not be "read"."
Now, if change the number of times the program goes through the for loop
from 20 to say 6, and hence calls Realloc fewer times, then the program
runs without any problems. It does not seem to have anything to do with
the size of the memory being allocated as I changed the size of the total
memory being allocated with a "for" loop with only 6 iterations to
something that is substantially larger than the memory being allocated in
the "for" loop when calling Realloc twenty times and the program ran
successfully. Has anyone else come across this problem or knows about some
sort of limitation on using "Realloc" that is not specified in the R
documentation?
Any help would be greatly appreciated.
Yours sincerely
Adam Kowalewski
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.