Sample code. Why can I access this NSString object after I released it?

I just wrote some research code to reinforce my understanding of Objective-C, and I came across this example, which I did not quite understand. I define this method and run the code:

- (NSString *)stringMethod
{
    NSString *stringPointer = [[NSString alloc] initWithFormat:@"string inside stringPointer"];
    [stringPointer release];
    [stringPointer release];
    NSLog(@"retain count of stringPointer is %i", [stringPointer retainCount]);
    return stringPointer;
}

After running the code and calling this method, I noticed several things:

  • Usually, if I try to access something that is supposedly freed after reaching zero, I get an EXC_BAD_ACCESS error. Here, instead, I get malloc "double free". Why is this?

  • No matter how many “[stringPointer release]” lines I add to the code, NSLog tells me to keep the number 1. When I add more releases, I just get more “double free” errors. Why are release statements not working properly?

  • Although I exceeded stringPointer and got a bunch of “double free” errors, the return value still works as if nothing had happened (I have another NSLog in the main code that reports the return value). The program continues to work normally. Again, can someone explain why this is happening?

These examples are pretty trivial, but I'm trying to understand what is going on. Thanks!

+3
source share
3

, dealloc. = P

, , , , . , ​​, - . ( ) .

, : ( dealloc'ing) . .

+6

. -, , . . - , , .

NSString , , , alloc/init, NSString, NSString. "" , C-. , , C.

[ stringPointer] , , . , .

+3

KeepCount always prints one, probably due to optimization - when the release notifies that it will be released, there is no reason to update keepCount to zero (since no one should reference the object at the moment), and instead, keeping keepCount simply cancels it.

0
source

Source: https://habr.com/ru/post/1719473/


All Articles