[R] R_alloc with structures with "flexible array members"

From: Ramon Diaz-Uriarte <rdiaz02_at_gmail.com>
Date: Wed, 05 Mar 2008 11:25:06 +0100

Dear All,

In a package, I want to use some C code where I am using a structure (as the basic element of a linked list) with flexible array members. Basically, this is a structure where the last component is an incomplete array type (e.g., Harbison & Steel, "C, a reference manual, 5th ed.", p. 159) such as:

struct Sequence {
  struct Sequence *next;
  int len;
  unsigned int state_count[];

To create one such sequence, I allocate storage (following Harbison and Steel) in a C program as follows:

struct Sequence *A;
int n = 4;
A = malloc( sizeof(struct Sequence) + n * sizeof(unsigned int));

If I understand correctly, however, it would be better to use R_alloc instead of malloc (memory automagically freed on exit and error; error-checking). But I do not know how to make the call to R_alloc here, since R_alloc allocates n units of size bytes each.

I've tried, without success, the following two:

int to_add_for_R_alloc =

    (int) ceil((float) sizeof(struct sequence) / sizeof(unsigned int));

  A = (struct sequence *) R_alloc(to_add_for_R_alloc + n, sizeof(unsigned int));

or even a brute force attempt as:

 A = (struct sequence *) R_alloc( 100, sizeof(struct sequence));

but both result in segmentation faults.

Should I just keep using malloc (and free at end)?



Ramon Diaz-Uriarte
Statistical Computing Team
Structural Biology and Biocomputing Programme
Spanish National Cancer Centre (CNIO)

R-help_at_r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Wed 05 Mar 2008 - 10:27:19 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 05 Mar 2008 - 17:30:18 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive