Reputation: 11
Below is the code
Thing *thingA = [[Thing alloc] init];
thingA.name = @"paper";
Thing *things[0];
things[0] = thingA;
NSLog(@"%@", things[0].name);
// output paper
[thingA release];
// here dealloc on Thing class is call
NSLog(@"%@", things[0].name);
// output paper yet
- Here I thought that this object would be nill
Why is the element things[0] that points to thingA pointer not nil, thus making the application crash? Why was thingA pointer not nil?
Upvotes: 0
Views: 113
Reputation: 15597
You're right in thinking that the memory for thingA
has already been deallocated by the time execution reaches the final NSLog
statement, but there's no guarantee that the operating system has marked it as invalid at that point. Since the value you placed at that address is still there, and thingA
is still a pointer to that value, the NSLog
statement still works.
The operating system doesn't automatically set local variables to nil
if the memory they refer to gets deallocated. That's one of the reasons pointer variables can be dangerous. If you like, you can programmatically set these variable to nil
yourself after sending a release
message, particularly if there's any chance they will be used again in the same block of code.
Upvotes: 1
Reputation: 2072
If I remember right, Objective-C will not release the memory if there are still other objects/variables referencing that location.
However, it is crashing because your array Still has the memory location address which no longer is available for referencing and thus crashing when you try to acces with thing[0].name
Hope this helps.
Upvotes: 1