geminiCoder
geminiCoder

Reputation: 2906

init, alloc and retain and "the initial value is never read"

Ive have used the static analyser to look through my code and have arrived at the following question.

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

This give me a memory error saying that the initial value is never read. I replaced it with the following

NSString *string = [[object name]retain];

Is this better/correct coding?

Cheers

Upvotes: 2

Views: 257

Answers (3)

JeremyP
JeremyP

Reputation: 86651

Your variable string is actually a pointer to an NSString object. The first line of your code created a new empty string and assigned a pointer to it to string. The second line of code then immediately overwrites that pointer with a pointer to a completely different string. You have never read the original value, and there is no way to access the allocated NSString, thus it has leaked.

The second option is correct., provided you release/autorelease it somewhere later.

Upvotes: 3

hypercrypt
hypercrypt

Reputation: 15376

I have seen someone else do this exact thing. NSString *string = [[NSString alloc] init]; creates a new object and assigns it to string. string = [object name]; Assigns the name of object to string. It is similar to saying int a = 0; a = 4, 0 has no effect on the 4. The problem with your code is that [[NSString alloc] init] creates a new object with a retain count of 1, because you do not release it it leaks. [object name] returns an autoreleased object which will disappear at the end of the runloop.

In short, use NSString *string = [[object name] retain];

Upvotes: 2

Nekto
Nekto

Reputation: 17877

This code:

1: NSString *string = [[NSString alloc] init];
2: string = [object name];

is incorrect because in line 1: you allocate new memory and store reference to it in variable string. In line 2: you store in variable string reference to another memory location.

As a result, you didn't read memory value that was allocated at line 1: and even didn't release it. So moreover you have memory leak there.

If you want to save reference to some place in memory you don't need alloc+init. You should use alloc+init when you want to allocate some space in memory where you will write data or read from.

Upvotes: 3

Related Questions