R_alloc 和对齐注意事项

R_alloc and alignment considerations

我正在编写一个 R 扩展,它要求我为结构数组分配内存。这些结构包含整数、SEXP、字符指针,例如类似于:

struct my_struct {
  int a;
  SEXP b;
  const char * d;
  const char * e[3];
};

我希望使用如下方式为数组分配内存:

struct my_struct * arr = (struct my_struct *) R_alloc(10, sizeof(my_struct));

这在最严格的意义上是有效的,但是 WRE 的以下评论让我暂停:

The memory returned is only guaranteed to be aligned as required for double pointers: take precautions if casting to a pointer which needs more.

我不关心速度或 space 因为我不希望我的数组很大或访问频繁。但是我确实想避免崩溃。我的理解是,未对齐的内存访问实际上只是 x86 架构的性能问题。此外,由于现在看来 R 主要用于 x86 架构(基于 CRAN 测试),而且我不关心性能,所以我这样做应该没有任何问题。

我是不是在给自己惹麻烦?


编辑:我在这里假设 "double pointers" 表示指向双精度的指针,而不是指向指针的指针,这在某些地方似乎是非正式约定。 FWIW R_alloc (src/main/memory.c@~2700) 中的代码想要分配 sizeof(VECREC) 的倍数,其中 VECRECunion(SEXP, double) (src/include/Defn.h@~410), 加上 header 偏移量。大概这是双打对齐保证的来源,但我不确定为什么这对于较大的结构来说会是个问题。当然,我在这方面不是特别有经验。

我仍然不是这方面的专家,但至少 this site:

In general, a struct instance will have the alignment of its widest scalar member. Compilers do this as the easiest way to ensure that all the members are self-aligned for fast access.

所以在这种情况下,该结构应该具有与 R_alloc 分配的内容兼容的对齐方式,因为它的最大成员将是 SEXP(可能,我猜 char * 在某些系统上更大,但似乎不太可能),并且 R_allocunion(SEXP, double) 的倍数分配,如问题中所述。

另一件可能值得指出的事情是,结构中元素的推荐顺序是从最大对齐要求到最低对齐要求,现在我们从 int 开始,这是最小的。