简体   繁体   中英

Passing Object to Unallocated Pointer

Let's say that I have declared an NSString like this

NSString *myString = [[NSString alloc] initWithString:@"Never Heard"];
NSString *tempString;

tempString = myString;

[myString release];

My question is why does it work? As you can see, I didn't alloc for the tempString. Therefore I don't think there is a need to release it. But if I try to alloc and init the tempString, it will bring an error.

NSString *myString = [[NSString alloc] initWithString:@"Never Heard"];
NSString *tempString = [[NSString alloc] init];

tempString = myString;

[myString release];

I use NSString as example, but instead I have different classes implemented. I'm trying to emphasize how memory allocation works here. Care to clarify and explain?

A pointer is simply a memory address. You only create one object, and then you point tempString to that object. And tempString == myString .

[myString release] deallocates the string, leaving both pointers pointing at deallocated memory.

Do no confuse variables with objects. Variables are simply are handles that you use to access objects. Creating a new variable does not mean you are creating a new object.

This is absolutely not about memory allocation. This is all about how pointers work. When you do this:

tempString = myString;

tempString points to the same object as myString. So calling any method on tempString is the same as calling them on myString.

tempString = myString;

In the above statement both myString, tempString are pointing to the location where "Never Hard" is stored. So, there is no error.

And I didn't understand when you meant - "But if I try to alloc and init the tempString, it will bring an error."

Edit 1

The second code snippet is an example of memory leak. tempString is allocated memory location. Let's work on with example -

myString -> MemoryLocation_1 that has "Never Hard"
tempString -> MemoryLocation_2 and the location it is pointing to isn't intialized with any value.

Now, with this statement -
tempString = myString;

Both myString  and tempString -> MemoryLocation_1 that has "Never Hard"

What about the MemoryLocation_2 obtained from the free store. It isn't returned back to free store and is lying there which no program can access to until the program termination. Thus giving memory leak . Hope it helps to an extent to understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM