Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it an "exc_bad_access" and not a "run-time" or "compile-time" error?

ScreenShot : running mode of xCode 5.1

Why is it an exc_bad_access and not a run-time or compile-time error?

By mistake I wrote "@age" instead of @"age", and it sparked my curiosity.

What I understand of exc_bad_access is that : Bad-Access is caused by a pointer (okay reference) that is dereferenced to a memory location which is either not allocated yet or deallocated or unauthorized to access (const or something).

But in this case I am only writing data onto memory and the syntax doesn't match the NS Objective-c format. Hence it should be a run-time error instead of a Bad-Access.

Where am I missing the concept?


1 Answers

The reason you get EXC_BAD_ACCESS is that the -initWithObjects: method expects all of its arguments to be valid Objective-C objects. Each Objective-C object starts with a small header; this used to be a straightforward pointer, called isa, to its class object (it isn't necessarily quite this simple any more, and these days you shouldn't poke about yourself; there are Objective-C runtime APIs you can use instead if necessary).

The reason you don't get a compiler error here is that there is no way in C/C++/Objective-C to specify the correct types for a "varargs" method or function. As a result, the compiler allows you to pass arguments of any type, assuming you know what you’re doing.

Anyway, within the implementation of -initWithObjects:, it’s going to try to send a -retain message to each of the objects you pass in. When it does that, it's going to try to dereference the isa pointer. In the case of your C string, that means it's going to treat the first four or eight bytes of the string as a pointer. This is very unlikely to have a good outcome, and very likely you'll get EXC_BAD_ACCESS straight away. Even if you were lucky and they do happen to point to valid memory, the Objective-C runtime is going to expect them to point to a valid Class structure, which is tremendously unlikely, and the result of that is also very probably going to be an EXC_BAD_ACCESS.

like image 197
al45tair Avatar answered Sep 15 '25 00:09

al45tair