Getting .size() of empty OwnedArray causes crash

“Title says all”. Or, well, most.

This is happening to me in an audio plugin, but I assume it’s a generic issue.

When I instantiate an OwnedArray and then check its size somewhere, the plugin and host will crash immediately if the OwnedArray doesn’t contain any items. I always have to dance around the crash by nesting the most simple .size() checks in if(!thing.isEmpty()) blocks.

Is this an intentional crash?
Couldn’t/shouldn’t the .size() of an empty OwnedArray just return const int 0?


Of course it does!

The only way you could get it to crash would be if you’ve done something silly, probably used a dangling pointer to the array, or corrupted the memory that holds it.

Not really.

I do something like this in my .h file:

OwnedArray<TypeOfThing> things;

That, to me, means: the variable things is now prepared to take items of the type TypeOfThing, but doesn’t contain any actual items yet. Correct?

In my .cpp file, at some point I want to check the size of the array, not necessarily if it’s empty, just the size. So I write something like this:

unsigned int someNumber=4;
if(things.size()>someNumber){/* do something with items */}

But this crashes the host and plugin immediately, at least if the OwnedArray doesn’t contain any items yet, and the OSX crash report tells me the issue lies in that .size() comparison.

The crash can only be avoided if I wrap the .size() check with an if() block:

unsigned int someNumber=4;
  if(things.size()>someNumber){/* do something with items */}

No crash like that, but I think it’s pretty clunky and a PITA to always remember and do. :confused:

I’m pretty sure I don’t have any loose pointers flying around, because I don’t even get to the point of actually putting things into the OwnedArray before it crashes from the .size() check.

(Edited several times for sense and consistency.)

Well OwnedArray::isEmpty() just calls OwnedArray::size() so there must be something else going on in your code…

1 Like

Don’t trust your IDE. If I have things completely illogical (like this is!), I do make clean (Clean build, or CMD-Shift-K, or what your IDE uses), restart the IDE, and compile again.
I’ve seen things like that in both, VisualStudio / Intellisense as well as in XCode. Sometimes the crash pointer shows the wrong line / statement.

If this additional if statement changes the behaviour, there might be a concurrency issue? Do you access this array from different threads?

Good luck