Andrey Chernukha
Andrey Chernukha

Reputation: 21808

Releasing object which is not allocated without any error

I've found that in my code i release object which had never been allocated and i do not get any error. The app doesn't crash. Everything works. I use Product -> Analyze and it tells me everything is all right.

I used to think releasing not allocated object leads to app crash. So my question is - should program crash when not allocated object is released (i.e I've missed something essential in my code which results in such a behavior) or everything runs as it is supposed to?

Upvotes: 1

Views: 265

Answers (2)

Eduardo Scoz
Eduardo Scoz

Reputation: 24743

If you haven't allocated the memory for your object, your object points to nil. When you call

[myobj release]

you're really sending the message to release to a nil object. Obj-C doesn't do anything in that case, and that's why your app doesn't crash.

Upvotes: 1

Ryan Wersal
Ryan Wersal

Reputation: 3228

It all depends on if the pointer to the "unallocated" object is nil. In Objective-C, a message sent to nil does nothing. The app crash is caused by sending a message to a dangling pointer (or a garbage pointer etc).

Upvotes: 2

Related Questions