views:

43

answers:

1

Hi guys,

here is the problem, today I had a bad time debugging my project, the console said: [CFString release]: message sent to deallocated instance 0x12345

I found the problem, and also, the solution, but I'm not sure why the error happened.

-(BOOL) sendRequest:(NSString *) message {
 //xml -> data
 NSString *xml = [self toXML:message ];
 NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

 NSMutableURLRequest *request=[[NSMutableURLRequest alloc] init];
 [request setURL: [NSURL URLWithString:url] ];
 [request setHTTPMethod:@"POST"];
 [request setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
 [request setValue:[NSString stringWithFormat:@"%d", [data length]] forHTTPHeaderField:@"Content-Length"];
 [request setHTTPBody:data];

    // some code NOT related to the connection... (UI stuff)

 //finally.. send the request
 NSURLResponse *theResponse;
 NSError *error;
 NSData *resp=[NSURLConnection sendSynchronousRequest: request returningResponse:&theResponse error:&error];

 //[data release];
 //[xml release]; <-- if i uncomment this; i got the memory issue 

 if ( resp == nil ){
  return NO;
 }
    // some code that updates the UI
 return YES; 
}

so, my question is why releasing xml: [xml release], provocates the horrible memory leak?. I thought that: since I was not using xml content anymore, it was a good practice to release it.

+2  A: 

XML is a passed parameter here. You don't own it, and thus shouldn't release it.

Joshua Weinberg
subzero
A general rule is that you should not `release` something unless you `alloc` it (among other things).ie `NSSomething *foo = [NSSomething somethingWithBlah:...];` doesn't need to be `release`d, but `NSSomething *foo = [[NSSomething alloc] init];` does.
dc
Assuming `toXML:` is following naming conventions, its autoreleased, which is why when you release it explicitly your'e causing an overrelease.
Joshua Weinberg
thanks @Joshua: you're right
subzero