user3017039
user3017039

Reputation: 27

malloc and memory leaks in objective c

I have a problem with memory leaks when using malloc in objective c. here's the 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
         */

        for (int i = 0; i<6; i++) {
            bufferData[i] = nil;
        }
        fieldCount = 0;
    }

    bufferData[fieldCount] = malloc(helloworld.length);
    char *ptrBuff = bufferData[fieldCount];

    for (int i = 0; i<helloworld.length; i++) {
        *ptrBuff++ = [helloworld characterAtIndex:i];
    }

    [self printBuffer];
    fieldCount ++;
}

-(void)printBuffer
{
    NSLog(@"buffer data %ld = %s",(long)fieldCount,bufferData[fieldCount]);
}

So basically I have 4 following classes below:

  1. ViewController -> UIViewController
  2. RootClass -> NSObject
  3. ChildClass1 -> RootClass
  4. Child -> Root Class

Additionally:

When I check my memory instrument, I have found a leak object every time it called
-addField method. It refers to this statement:

malloc(sizeof(*bufferData));

Can somebody help to solve my problem?

Upvotes: 1

Views: 681

Answers (1)

Alfonso
Alfonso

Reputation: 8502

I assume with malloc(sizeof(*bufferData)) you meant malloc(helloworld.length) above (since that's the only malloc call I see in your example).

The memory leak occurs when you clear your buffer:

bufferData[i] = nil;

This leaks because you allocated the buffer contents using malloc but did not free them later using free. Note that even under ARC you must free any malloced resources yourself. ARC only provides management for Objective-C object instances.

The correct way to free the buffer here is:

free(bufferData[i]);
bufferData[i] = NULL;

Upvotes: 3

Related Questions