简体   繁体   English

从 R 语言调用的 C 函数中的动态内存分配

[英]Dynamic memory allocation in C functions called from R language

I'm writing an R package that calls a C script.我正在编写一个调用 C 脚本的 R 包。 The C script uses a structure with a dynamically determined length: the length of the array forest->edges depends on the data passed from R. C 脚本使用动态确定长度的结构:数组forest->edges的长度取决于从 R 传递的数据。

typedef struct {
  unsigned int n_edge;
  ...
  unsigned int max_node;
  unsigned int edges[];
} forest;

forest * forest_new (unsigned int *n_edge) {
  forest *f = malloc(sizeof(forest) + (2 * *n_edge * sizeof(int)));
  f->n_edge     = *n_edge;
  ...
  f->max_node   = 0;
  return f;
}

The code runs successfully in C, but crashes when an R call triggers forest_new .代码在 C 中成功运行,但在 R 调用触发forest_new时崩溃。 My hunch is that the crash results from memory allocation, and indeed the R manual mentions alternative means of allocating memory (eg R_alloc , Calloc ), which threads elsewhere seems to suggest should be used in place of malloc / calloc .我的直觉是从内存分配的碰撞结果,并且实际上ř手册提到分配存储器的替代手段(例如R_allocCalloc ),该线程 别处似乎表明应该代替使用malloc / calloc

So part 1 of the question is when calls to malloc / calloc should, or must, be replaced by R-safe equivalents (perhaps they are irrelevant to my problem?).所以问题的第 1 部分是对malloc / calloc调用何时应该或必须被 R 安全等价物替换(也许它们与我的问题无关?)。 Part 2 of the question is how the R-safe functions can handle structures whose length is dynamically determined.问题的第 2 部分是 R 安全函数如何处理长度是动态确定的结构。

You can use malloc/calloc and free in packages to allocate and free memory, but you have to handle out of memory errors like in any C application.您可以在包中使用malloc/callocfree来分配和释放内存,但您必须像在任何 C 应用程序中一样处理内存不足错误。 You can use Calloc/Free/Realloc provided by R and then you will get the error handled in the "R way" (an R error when out of memory).您可以使用 R 提供的Calloc/Free/Realloc ,然后您将获得以“R 方式”处理的错误(内存不足时的 R 错误)。 The R_alloc function allows you to allocate temporary data that is freed automatically when your external function exits (when you get back to R, it is stack-based allocation). R_alloc函数允许您分配在外部函数退出时自动释放的临时数据(当您返回 R 时,它是基于堆栈的分配)。

R does not care about whether your C code uses structures with dynamically determined length (flexible arrays), R does not access your structure at all. R 不关心您的 C 代码是否使用动态确定长度的结构(灵活数组),R 根本不访问您的结构。

If you need more help please post a self-contained example or provide more information about the error.如果您需要更多帮助,请发布一个独立的示例或提供有关错误的更多信息。 Perhaps it is also worth checking n_edge has a correct/sane value in forest_new .或许,这也是值得一试n_edge已经在正确的/理智值forest_new

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM