1

There's a point of memory management I'm not 100% clear on, suppose there is the following code:

{
NSString *string = [[NSString alloc] init];
string = [[NSString alloc] init];
}

Does this cause a memory leak of the first allocation? If not why not?

3 Answers 3

2

Under ARC, this does not leak memory. This is because any time a strong object pointer is changed, the compiler automatically sends a release to the old object. Local variables, like NSString *string, are strong by default.

So your code above gets compiled to something more like this:

{
NSString *string = [[NSString alloc] init];

// Oh, we're changing what `string` points to. Gotta release the old value.
[string release];
string = [[NSString alloc] init];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Does ARC releases it immediately or just put into the main autoreleasepool?
It releases it immediately, as soon as it determines the old value is not used anymore.
1

Conceptually, BJ is correct, but the generated code is slightly different. It goes something like this:

NSString *string = [[NSString alloc] init];

// Oh, we're changing what `string` points to. Gotta release the old value.
NSString *tmpString = string;
string = [[NSString alloc] init];
[tmpString release];
[string release]; // string goes out of scope at this point in your code

This order of operation is usually not that critical (and if you care too much about it, you are probably coding incorrectly). But understanding it explains why the objects are destroyed exactly when they are.

Comments

1

No it does not cause a leak. ARC will release the first string before it sets the second string. This is the truly amazing power of ARC!

1 Comment

Does ARC releases it immediately or just put into the main autoreleasepool?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.