Problem with iphone

This is a piece of code that I wrote in xcode

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

If I'm right, it should give a runtime error when the printmessage function is called, since myFoo is freed by this time. But in xcode, the code works and the print message gets called, is this a problem due to installation on xcode?

Relations Abhijit

+4
source share
2 answers

You invoke undefined behavior by accessing free memory.

It can break, it can work fine, it can cause dancing unicorns to burst from your nose.

To detect memory errors during code development, you must enable NSZombie, see instructions here:

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

Update

You may wonder why this works: of course, should the OS always throw an error when trying to access invalid memory?

The reason you don't always get the error (and why the behavior is undefined) is because the memory check is valid on every access, it will lead to performance degradation - i.e. the code will run slower, just to test for something that should never be.

Therefore, you must be careful to catch all these errors during development so that they never happen to the end user. NSZombies are the best tool to find them.

Another point - if you do β€œbuild and parse” in xcode, it may also find this error during build. Of course, the static analyzer detects some memory errors during assembly.

+7
source

The release of the object does not happen instantly, the object will be released, but you cannot be sure that it is sending a release message. The behavior you experience is normal.

0
source

All Articles