Objective-C 大型数组初始化时插件崩溃

Objective-C plugin crashes with initialization of large array

我正在 objective-C 开发一个插件,我在 Osirix 运行。在插件中的某个时刻,我初始化了两个大数组(这意味着接受一个 512x512 图像,稍后将其输入到 CoreML 模型中)。原始插件使用 coreml 模型接受 200x200 大小的图像,var IMG_SQSIZE 设置为 200^2 并且一切正常。现在我已将 IMG_SQSIZE 增加到 512^2 但这会使插件崩溃。如果我在没有崩溃之后进行数组初始化和所有内容,如果我保留此行但在崩溃仍然存在后删除所有内容......所以我得出结论,这是导致问题的原因。我是 Objective-C 和 X-code 的新手,但这似乎是一个内存问题。我想知道这是否是我需要在代码中分配的内存(构建良好)或者这是否是程序 运行 插件的问题。任何建议都很好,谢谢

#define IMG_SQSIZE      262144 //(512^2)

double tmp_var[IMG_SQSIZE], tmp_var2[IMG_SQSIZE];

请注意,512^2 比 200^2 大很多,我怀疑你这样做是内存问题。

您应该使用 malloc 分配内存并将代码移至 C。这是我根据要求提出的建议 - 大量内存和双精度数组。如果你可以在这里使用浮点数甚至整数,它也会大大减少资源需求,所以看看它是否可行。

至少在 Objective-C 中这很容易做到,但您也应该将所有这些都包装在它自己的 autoreleasepool 中。

让我们先试试简单的方法。查看以下是否有效。

// Allocate the memory
tmp_var  = malloc( IMG_SQSIZE * sizeof( double ) );
tmp_var2 = malloc( IMG_SQSIZE * sizeof( double ) );

if ( tmp_var && tmp_var2 )
{
  // ... do stuff
  // ... see if it works
  // ... if it crashes you have trouble
  // ... when done free - below
}
else
{
  // Needs better handling but for now just to test
  NSLog( @"Out of memory" );
}

// You must to call this, ensure you do not return
// without passing here
free ( tmp_var  );
free ( tmp_var2 );

编辑

这是另一个执行单个 malloc 的版本。不确定哪个更好,但值得一试......如果内存不是问题,这个应该表现更好。

// Supersizeme
tmp_var = malloc( 2 * IMG_SQSIZE * sizeof( double ) );

if ( tmp_var )
{
  // This points to the latter portion
  tmp_var2 = tmp_var + IMG_SZSIZE;

  // ... do stuff
  // ... see if it works
  // ... if it crashes you have trouble
  // ... when done free - below
}
else
{
  // Needs better handling but for now just to test
  NSLog( @"Out of memory" );
}

// You must to call this, ensure you do not return
// without passing here
free ( tmp_var );

此外,在这两种情况下,您都需要将变量定义为

double * tmp_var;
double * tmp_var2;