0

Maintaining some code from an iOS application, I came upon the following:

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);

Here we are doing allocation of two struct arrays of dynamic size (cannot determine size at compile time). So called "Variable-length array", based on that SO question ( Declare Dynamic Array ).

I'm well aware that this does not even compile in C/C++ and when looking after similar questions, the answer is often "Use malloc" or "Use NS(Mutable)Array".

But I haven't really found the answer to the question:

What happens in Objective C when declaring int array[size]; ?

The reason I'm wondering is that the piece of code I have reproduced above crashes when using VLA with reasonably large sizes (36000) and does not crash when using malloc:

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

EDIT #1: What wikipedia says about VLA http://en.wikipedia.org/wiki/Variable-length_array

EDIT #2: Crashes are EXC_BAC_ACCESS at odd places in functionThatConvertsInputToOutput or on the line calling functionThatConvertsInputToOutput.

Community
  • 1
  • 1
Thibault D.
  • 10,041
  • 3
  • 25
  • 56

1 Answers1

2

It’s very likely it’s sticking the memory for the array on the stack, which is why you’re crashing when you blow up the stack by 36,000 * sizeof(CLLocationCoordinate2D).

Wil Shipley
  • 9,343
  • 35
  • 59
  • Ok, looks like the stack for an iOS secondary thread is about 512KB, so max 32'000 records of my 16bytes struct. Seems to explain the issue. Thanks :) – Thibault D. Jan 13 '14 at 12:24