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

标签 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不太了解,希望有人能告诉我这里发生了什么。

最佳答案

您需要释放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
}

关于ios - 内存永远不会释放潜在的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16584027/

相关文章:

iOS9 Untrusted Enterprise Developer 没有信任选项

ios - Xcode 模拟器 - CyMemDef.dylib : mach-o, 但不是为 iOS 模拟器构建的

ios - 为什么在 Swift 上显示警报时需要 DispatchQueue?

iphone - 未找到 TapkuLibrary.h 和 <TapkuLibrary> - 词法和预处理器问题

iphone - 如何获取 subview 中导航栏的高度?

java - 这种场景适合WeakReferences吗?

objective-c - 包含可访问方法的 iOS 类

iphone - TableView 滚动异步

javascript - 识别 Javascript 堆之外的内存泄漏

ios - 仪器的色 block 是什么意思?