Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling 'release' too many times?

I was looking at someone else's code and noticed they called 'release' on an NSString they didn't own (never called alloc/retain/copy anywhere and it wasn't a property).

This looked a bit strange to me and it made me wonder if any strange behaviour can occur if you call 'release' on an object that you either don't 'own' or whose ref count is already 0? The code below compiles/runs fine without warnings so I'm guessing there's no problem but I was just curious.

// Releasing an object I don't own
NSString *notMyString = [NSString stringWithString:@"Not mine."];
[notMyString release]; // Ignored?

// Releasing an object I own, twice
NSString *myString = [[NSString alloc] initWithString:@"Mine."];
[myString release]; // Ref count = 0
[myString release]; // Ref count = ?
like image 914
nebs Avatar asked Jun 18 '10 16:06

nebs


1 Answers

Yeah, don't do that. Your assessment is correct, as is your understanding of the ownership rules. Sending a message to an already released object has undefined behavior-- sometimes you'll get lucky because of other stuff going on and nothing will happen. Sometimes you'll crash immediately, sometimes later because you've corrupted something else.

like image 130
Ben Zotto Avatar answered Oct 12 '22 12:10

Ben Zotto