Question About Memory Leaks & Releasing Objects

boyfarrell

Registered
Hi all.

If I initialise a new object inside a method but need to return that object can I return the object and then release it or does return have to be the last line of the method. i.e. in code:

Code:
#import <stdfitpopstar.h>

////

@interface Bottom : Object
{
       char size[];
}

-(void) setLopez: (char[]) bumSize;
-(Bottom*) getLopezBumSize;

@end

////

@implementation

-(void) setLopez: (char[]) bumSize;
{
        size = bumSize;
                   
}

-(Bottom*) getLopezBumSize;
{
       Bottom *hugeArse = [[Bottom alloc] init];
       
       char[] botbot = "full-bodied";
       [hugeArse setLopez: botbot];
       
 [B]  return hugeArse;

       [hugeArse free];[/B]
 
}
@end

////

int main (int argc, char *argv[])
{

         Bottom *JLO = [[Bottom alloc] init];
         JLO = [JLO getLopezBumSize];
         [JLO free];

         return 0;
}
Sorry, got a bit bored by the end so code wise it probably doesn't make sense. However, the important bit is in bold - can I do this with out a leak? The compiler doesn't complain.

Cheers, Daniel.
 

kainjow

Registered
No.

Whenever "return" is called in a method/function, it ends the function. Any code after that is not executed.

What you need is the "autorelease" method. This will free up the memory when the time is right.

Code:
-(Bottom*) getLopezBumSize;
{
       Bottom *hugeArse = [[Bottom alloc] init];
       
       char[] botbot = "full-bodied";
       [hugeArse setLopez: botbot];
       
       return [hugeArse autorelease];
}
 

boyfarrell

Registered
Great, thanks.

I'll convert the code over to NSObject as my root then.

Dan
 
Top