abhijit
abhijit

Reputation: 41

iphone memory management strange issue

This is a piece of code I had written in xcode

Foo * myFoo = [[Foo alloc] init] ;

[myFoo release] ;
[myFoo printMessage] ;

If I am right, it should give a runtime error when printmessage function is called as myFoo gets deallocated by that time. But in xcode , the code is working and print message is getting called, is it a problem due to setting on xcode?

Regards Abhijit

Upvotes: 4

Views: 80

Answers (2)

JosephH
JosephH

Reputation: 37505

You're invoking undefined behaviour by accessing freed memory.

It might crash, it might work fine, it might result in dancing unicorns spewing forth from your nose.

To detect memory errors whilst you're developing code, you should enable NSZombie's, see instructions here:

http://www.cocoadev.com/index.pl?NSZombieEnabled

Update

You might wonder why it works like this - surely the OS should always throw an error when you try to access memory that isn't valid?

The reason why you don't always get an error (and why the behaviour is undefined) is that checking the memory is valid on every access would result in a performance penalty - ie. the code would run slower, just to check for something that shouldn't ever happen.

Hence you must be careful to trap all these errors during development, so that they never happen for an end user. NSZombies is the best tool for finding them.

One other point - if you do "build and analyze" in xcode, it might also find this error at build time. Certainly the static analyzer will detect some memory errors at build time.

Upvotes: 7

ynnckcmprnl
ynnckcmprnl

Reputation: 4352

Releasing an object is not instantaneous, the object will be released, but one can't be sure that it's when one sends a release message. The behavior you're experiencing is normal.

Upvotes: 0

Related Questions