简体   繁体   中英

Leak during the creation of a NsMutableData

During the creation of a NSMutableData i have a leak. I release webData2 in the connectionDidFinishLoading...

webData2 = [[NSMutableData alloc]init];

So I have test this :

NSMutableData *test =[[NSMutableData alloc]init];
webData2 = test;
[test release];

and I have a leak on the instruction : NSMutableData *test =[[NSMutableData alloc]init];

I don't understand ! anyone have an idea ?

Thank you!

GT

This will not work, the reference in webData2 is the same as test and will be released.

  1. webData2 = [[NSMutableData alloc]init]; // webData2 points to object A
  2. NSMutableData* test = [[NSMutableData alloc] init]; // test points to object B
  3. webData2 = test; // test and webData2 both points to A, nothing points to B
  4. [test release]; // object B is released, test and webData2 points to garbage

So the problem is at line 3, where you no longer have an explicit reference to object B allocated at line 1.

You need to release webData2 before assigning it with a new object pointer.

As bbum points out the leak is always referring to where the object is allocated, not where it is actually leaked.

When in doubt use the static analyzer (actually always run the static analyzer from time to time). You will find it in Xcode under the Build menu as Build and Analyze . It will among many errors find most memory leaks, and mark them with blue arrows in the margin. Expanding the arrows will show the complete program flow for the leak from the allocation to the last reference getting lost.

what you can do is:

NSMutableData *test =[[NSMutableData alloc]init];
webData2 = [test copy];
[test release];

then webData2 will not get released together with test... you will have to release it later.

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