内存永远不会释放潜在的内存泄漏

时间:2013-05-16 09:42:34

标签: ios objective-c memory-leaks

刚刚在我的应用上运行了analyze并且它抛出了这个内存错误并指向了以下代码中的return行:

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
}

我不太了解C并且希望有人能分辨出这里发生了什么。

2 个答案:

答案 0 :(得分:4)

您不是free在此行中分配的缓冲区msgBuffer

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

答案 1 :(得分:3)

您需要释放msgBuffer

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

可能是你可以在返回之前做到

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