Tuesday, 15 July 2014

automatic ref counting - malloc and memory leaks in objective c -



automatic ref counting - malloc and memory leaks in objective c -

i have problem memory leaks when using malloc in objective c. here's code:

.h (interface)

{ char *buffer[6]; nsinteger fieldcount; } -(void)addfield:(nsstring *)str;

.m (implementation)

-(void)addfield:(nsstring *)str { nsstring *helloworld =str; if (bufferdata[5] != nil) { /* clear buffer */ (int = 0; i<6; i++) { bufferdata[i] = nil; } fieldcount = 0; } bufferdata[fieldcount] = malloc(helloworld.length); char *ptrbuff = bufferdata[fieldcount]; (int = 0; i<helloworld.length; i++) { *ptrbuff++ = [helloworld characteratindex:i]; } [self printbuffer]; fieldcount ++; } -(void)printbuffer { nslog(@"buffer info %ld = %s",(long)fieldcount,bufferdata[fieldcount]); }

so have 4 next classes below:

viewcontroller -> uiviewcontroller rootclass -> nsobject childclass1 -> rootclass child -> root class

additionally:

init process of 3 classes within -viewdidload method. both childclass1 , childclass 2 have timer phone call -addfield method @ same time.

when check memory instrument, have found leak object every time called -addfield method. refers statement:

malloc(sizeof(*bufferdata));

can help solve problem?

i assume malloc(sizeof(*bufferdata)) meant malloc(helloworld.length) above (since that's malloc phone call see in example).

the memory leak occurs when clear buffer:

bufferdata[i] = nil;

this leaks because allocated buffer contents using malloc did not free them later using free. note under arc must free malloced resources yourself. arc provides management objective-c object instances.

the right way free buffer here is:

free(bufferdata[i]); bufferdata[i] = null;

memory-management automatic-ref-counting

No comments:

Post a Comment