开发者

Leak during the creation of a NsMutableData

开发者 https://www.devze.com 2023-03-04 17:27 出处:网络
During the creation of a NSMutableData i have a leak. I release webData2 in the connectionDidFinishLoading...

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消