【问题标题】:VLA Variable-length array in Objective C (iOS), what happens?Objective C(iOS)中的VLA可变长度数组,会发生什么?
【发布时间】:2014-01-13 10:46:24
【问题描述】:

维护iOS应用程序的一些代码,我遇到了以下问题:

CLLocationCoordinate2D inputArray[size]; // CLLocationCoordinate2D is a struct containing two doubles
for (int i = 0; i < size; i++) {
    inputArray[i] = ... ; // Fill the array
}
CLLocationCoordinate2D outputArray[size];
functionThatConvertsInputToOutput(inputArray, outputArray, size);

这里我们正在分配两个动态大小的结构数组(无法在编译时确定大小)。所谓的“可变长度数组”,基于那个 SO 问题 (Declare Dynamic Array)。

我很清楚这甚至不能在 C/C++ 中编译,并且在处理类似问题时,答案通常是“使用 malloc”或“使用 NS(Mutable)Array”。

但我还没有真正找到问题的答案:

在声明 int array[size]; 时,Objective C 中会发生什么?

我想知道的原因是,我在上面复制的这段代码在使用具有相当大尺寸 (36000) 的 VLA 时会崩溃,而在使用 malloc 时不会崩溃:

CLLocationCoordinate2D *inputArray = malloc(sizeof(CLLocationCoordinate2D) * size);
CLLocationCoordinate2D *ouputArray = malloc(sizeof(CLLocationCoordinate2D) * size);

编辑#1:维基百科对 VLA http://en.wikipedia.org/wiki/Variable-length_array 的评价

编辑#2:崩溃是EXC_BAC_ACCESSfunctionThatConvertsInputToOutput 的奇怪位置或在调用functionThatConvertsInputToOutput 的线路上。

【问题讨论】:

  • Objective-C 是基于 C 的,所以它在 C 和 Objective-C 中支持。如果您不喜欢它(我不喜欢),请使用malloc() 和朋友。
  • 那不是我不喜欢它。只是,我似乎在使用 VLA 时遇到了与溢出相关的崩溃,我真的不明白为什么。
  • 我认为 Wil Shipley 已经回答了这个问题。
  • 没错 :) 谢谢!

标签: ios objective-c arrays cocoa


【解决方案1】:

很可能它会将数组的内存粘在堆栈上,这就是为什么当您将堆栈炸毁 36,000 * sizeof(CLLocationCoordinate2D) 时会崩溃的原因。

【讨论】:

  • 好的,看起来 iOS 辅助线程的堆栈大约是 512KB,所以我的 16bytes 结构最多有 32'000 条记录。似乎解释了这个问题。谢谢:)
猜你喜欢
  • 2012-12-14
  • 1970-01-01
  • 2011-07-11
  • 2016-09-03
  • 2011-07-24
  • 2016-01-25
  • 2021-07-11
  • 2013-03-31
  • 1970-01-01
相关资源
最近更新 更多