2013-05-16 46 views
1

剛跑到我的應用程序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

永遠的'malloc()'類型的調用,最好有一個*可達*'免費()'*某處*完成後返回到實施。如果你沒有可用的'free()',你就有泄漏。這真的很簡單。 ('realloc()'不具備零大小)。 – WhozCraig

+0

+1,謝謝你的解釋。現在變得更有意義了。 – Robert

+1

在這種情況下,'malloc(length)'可以正常工作,但下面的'sysctl(...)'返回一個負值,那麼'msgbuffer'不會被釋放/釋放。所以可能確實存在內存泄漏,這不僅僅是分析器告訴你可能存在內存泄漏。 –

回答

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 
} 
+0

非常感謝。這似乎解決了它。 =)我會盡快接受你的回答。 – Robert

4

你是不是free荷蘭國際集團緩衝msgBuffer在這一行分配:

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

好的,+1! – borrrden

+0

非常感謝。 – Robert