From saptarshi.guha at gmail.com  Wed Apr  1 07:55:05 2009
From: saptarshi.guha at gmail.com (Saptarshi Guha)
Date: Wed, 1 Apr 2009 01:55:05 -0400
Subject: [Rd] Creating a VECSXP when n is unknown(using Linked list)
Message-ID: <1e7471d50903312255v477f8bf3t84886ad3941acb5@mail.gmail.com>

Hello,
I need to create a VECSXP(A) each element of which is a 2-element
VECSXP. Since I dont know
how many elements there will be i create a linked list of 2-element
VECSXP (see code at end)

Once I know the number of elements, i then go ahead allocVector A and
then SET_VECTOR_ELEMENT the
elements of A by iterating over the linked list.

Suppose the function is f(), then it works a couple of times but
crashes ( in different ways)
after that.
e.g
  for(x in 1:10){
    f(x)
      }
Then this crashes after a few iterations. If I were to perform just
one call, e.g u=f(x[1]),
i get a valid results.
Where am I going wrong? I must admit my C experience is very rough.


Thank you in advance
Saptarshi

  ==code==
struct ll_element {
    SEXP k,v;
    struct ll_element * next;
};
struct ll_element *elem,*head;
head=NULL;
unsigned long countofelems=0;
while(1){
    nextKV(jo,&val,&data,&len,&err);
    if(err && err!=2 ) {
      error("Problem reading:%d",err);
      return(R_NilValue);
    }
    if(err==2) {
      //Indicates no more values, we have all the elements we need
      //exit and make VECSXP
      break;
    }
    SEXP vxp;
    int Rerr;
    elem = (struct ll_element *)R_alloc(1,sizeof(struct ll_element));
    PROTECT(elem->k = NEW_NUMERIC(1));
    REAL(elem->k)[0]=(double)val;

    vxp = allocVector(RAWSXP,len);
    memcpy(RAW(vxp), data, sizeof(jbyte)*len);
    free(data);

    PROTECT(elem->v = R_tryEval(LCONS(install("unserialize"),CONS(vxp,
R_NilValue)), R_GlobalEnv, &Rerr));
    if(Rerr!=0){
      UNPROTECT(2);
      error("Could not unserialize");
      return(R_NilValue);
    }
    UNPROTECT(2);
    countofelems+=1;
    elem->next=head;
    head=elem;
  }
  struct ll_element *ce;
  SEXP rv;
  int k=0;
  ce=head;
  PROTECT(rv= allocVector(VECSXP, countofelems));
  while(ce){
    SEXP y ;
    PROTECT(y=allocVector(VECSXP,2));
    SET_VECTOR_ELT(y,0,ce->k);
    SET_VECTOR_ELT(y,1,ce->v);
    SET_VECTOR_ELT(rv,k,y);
    k+=1;
    ce=ce->next;
    UNPROTECT(1);
  }
  UNPROTECT(1);
  return(rv);



[Rd] Creating a VECSXP when n is unknown(using Linked list)
Saptarshi Guha