简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM