Manually how to deallocate an object (NSString / NSMutableString ,..) under ARC in Objective C

264 views Asked by At

Initialised an Object (NSString / NSMutableArray) and set value for that. I need to deallocate the object, then have to assign a value to that object to get an error of that's already been deallocated

Manually trying to produce the following error EXC_BAD_ACCESS_KERN_INVALID_ADDRESS 0x00-012cbb4bb0.
EXC_BAD_ACCESS_KERN_INVALID_ADDRESS 0x00-020.

2

There are 2 answers

0
Rob Napier On

What you're asking for is straightforward, but likely unhelpful to you.

__unsafe_unretained NSArray *array = [[NSArray alloc] initWithObjects:@"test", nil];
// Accessing `array` at this point will crash

It's important that you create a non-empty NSArray here. Empty NSArrays reference a singleton object that can't be deallocated. Similarly, don't use an array literal @[...], since those are stored directly in the binary and also can't be deallocated. Similar things are true with NSString.

That said, this is somewhat unlikely a good way to track down the bug you're describing. Start with ensuring there are no warnings in your code. Then run the static analyzer. Check the crash report (hopefully it will give you a hint what classes are involved). Then carefully inspect the usages of the thing you believe you're crashing on (search for its use in the program; look for things like __unsafe_unreatined or assign). Then turn on NSZombie (search for it; there are many tutorials on its use).

Also you may need to explore any C/C++ code, which can also create this exception. And you can get this exception if you've corrupted memory through unsafe threading. The exception just tells you that you're trying to access an invalid pointer, and that can come from many things. Over-released ObjC objects are a common cause, but not the only one.

0
user102008 On

Accessing unallocated memory is undefined behavior. Undefined behavior means that it isn't guaranteed to crash, or to do any specific thing. It might crash in one case and not in another. You can't rely on it to do anything.