A very nasty bug in Apple’s compiler?

Just ran into this recently. Took a while to work this out – it seems to be a bug in Apple’s compiler (either that, or I massively misunderstand the scoping rules Apple is using). I didn’t try analysing the assembler output – I didn’t have time, this was for a project that had to ship yesterday!

(this is on the Apple LLVM 3.1 compiler – as shipped with latest/current Xcode)

In this code:

NSArray* a = ...get array...

if( something that is true )
NSString* p = [a objectAtIndex:0];

// 1. What is "p" at this point?

NSLog( @"%@", [p uppercaseString] );

// 2. What is "p" at this point?

NSLog( @"%@", [p uppercaseString] );


UIViewController* p = self.presentingViewController;

…it turned out that “p” was simultaneously both variables, with both values (which I thought would be impossible, code-wise: they are defined in non-overlapping scopes). Even more strangely (c.f. below) … Apple seemd to flip-flop between which of the two variables it used at each moment.

Stepping through with the debugger, 2 lines (and one scope!) before the second “p” variable was even declared, it already existed *and already had been defined*.

Maybe this is an obscure piece of Objective-C lore, but it looks to me like a major violation of C rules (hence: I think it’s a pre-emptive performance optimization gone wrong).

NB: the first call to

[s uppercaseString]

worked fine. The second call crashed repeatedly complaining that UIViewController doesn’t conform to selector uppercaseString. It seems that at points “1.” and “2.” the dereferencing of “p” pointed first to the String pointer, and second to the UIVC pointer.

NB: the braces above are exactly as in the source.


Rename either of the variables and – unsurprisingly – things work as expected. It was a quick “fix” – but worrying that it was needed.

I have almost zero knowledge of the internals of modern C compilers – so if the above behaviour is actually correct, and my understanding is wrong, I’d love it if someone can point to an explanation for this.

2 thoughts on “A very nasty bug in Apple’s compiler?

Leave a Reply

Your email address will not be published. Required fields are marked *