1
votes

Just ran analyze on my app and it threw up this memory error and pointed to the return line in the following code:

int                 mgmtInfoBase[6];
char                *msgBuffer = NULL;
size_t              length;
unsigned char       macAddress[6];
struct if_msghdr    *interfaceMsgStruct;
struct sockaddr_dl  *socketStruct;
NSString            *errorFlag = NULL;

mgmtInfoBase[0] = CTL_NET;        // Request network subsystem
mgmtInfoBase[1] = AF_ROUTE;       // Routing table info
mgmtInfoBase[2] = 0;
mgmtInfoBase[3] = AF_LINK;        // Request link layer information
mgmtInfoBase[4] = NET_RT_IFLIST;  // Request all configured interfaces

if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
    errorFlag = @"if_nametoindex failure";
else
{
    if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
        errorFlag = @"sysctl mgmtInfoBase failure";
    else
    {
        if ((msgBuffer = malloc(length)) == NULL)
            errorFlag = @"buffer allocation failure";
        else
        {
            if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
                errorFlag = @"sysctl msgBuffer failure";
        }
    }
}

if (errorFlag != NULL)
{
    NSLog(@"Error: %@", errorFlag);        
    return errorFlag;                  // this line gives the memory leak warning
}

I don't know much C and was hoping someone could tell what's going on here.

2
For ever malloc()-type call, there better be a reachable free() somewhere to return it back to the implementation when finished. If you don't have a reachable free(), you have a leak. It really is that simple. (realloc() with a zero-size not withstanding).WhozCraig
+1 and thanks for the explanation. Makes a lot more sense now.Robert
In the event, that malloc(length) works fine but the following sysctl(...) returns a negative value, then msgbuffer will not be released/freed. So there may be really a memory leak, it is not just analyzer telling you there could be one.Hermann Klecker
@HermannKlecker: Thanks & +1. I'm learning here. =)Robert

2 Answers

4
votes

You are not free ing buffer msgBuffer allocated in this line:

if ((msgBuffer = malloc(length)) == NULL)
3
votes

You need to free msgBuffer

 if ((msgBuffer = malloc(length)) == NULL)

may be you can do it before just before return

if (errorFlag != NULL)
{
    free (msgBuffer); // Free here
    NSLog(@"Error: %@", errorFlag); 
    return errorFlag;                  // this line gives the memory leak warning
}