0

I wrote this code at the end of a long day:

MyObject *thisObj;
// ... lots of code here ...
thisObj.name = @"test"; // Which caused an EXC_BAD_ACCESS as I hadn't alloc / init'd thisObj.

It took me ages to figure out I'd forgotten to initialise the object so I was wondering - is there any way of catching this. I tried setting NSZombie but that didn't seem to do anything.

Any ideas on the best way to do this?

2
  • EXC_BAD_ACCESS actually is some sort of collection of errors. So it depends on the particular situation whether you can easily catch it or not (at all). For example, NSZombieEnabled won't work in every situation.
    – cutsoy
    Commented May 3, 2011 at 18:08
  • 3
    NSZombie tells you if you send a message to an object with a retain count of 0. It can't help you with uninitialized variables.
    – Lou Franco
    Commented May 3, 2011 at 18:09

1 Answer 1

5

Never declare a variable without initializing it to some value. Even

MyObject *thisObj = nil;

Is better than

MyObject *thisObj;

There's probably a compiler flag you can turn on to warn you about this.

EDIT:

Yep, you can use -wuninitialized -O (capital O, not 0) to get this:

enter image description here

1
  • Dave - thanks. I'm sure the compiler flag will come in very handy should I make a similar mistake at the end of another long day!
    – Snowcrash
    Commented May 3, 2011 at 21:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.