Objective-C object are not destroyed after release message

44 views Asked by At

I was confused by such output result of this program.

#import <Foundation/Foundation.h>
#import "Human.h"

int main(int argc, const char * argv[]) {
    Human *human = [Human new];

    [human release];

    [human sayHello];

    return 0;
}

The class itself is

@implementation Human

-(void)sayHello {
    NSLog(@"Hello");
}

-(void)dealloc {
    NSLog(@"Deallocated");
   [super dealloc];
}

@end

The result is Output result

The main question is why method sayHello was executed though object itself was destroyed as its retain count was set to 0 by sending release message? What's more important that if I go through the program flow via debugger, the application will crash cause human pointer is not an object anymore. What's happening here?

P.S. ARC is turned off

Thanks in advance.

1

There are 1 answers

3
bbum On BEST ANSWER

Welcome to C! There are no safety guards here.

When memory is deallocated, the compiler and runtime don't, by default, do anything special other than to mark the memory as available for use by something else.

Whatever is in the memory remains in the memory and, as you've discovered, said memory can still be read from and that can lead to very nasty bugs.

In Xcode, you can turn on zombie detection that would cause this particular bug to be highlighted at runtime by the tools.

There is also malloc scribbling/debugging, which would also catch this.

See here: https://developer.apple.com/library/archive/documentation/Performance/Conceptual/ManagingMemory/Articles/MallocDebug.html