2010-07-16 38 views
0

我有这样的代码:的ipad,需要有一个内存泄漏的帮助

void getStringWithTag(char* pFile, long sizeSound, char* tag, char* ret, float* currentPos){ 
char* tagCopy; 
tagCopy = (char*)malloc(256 * sizeof(char)); 
int totalLen = 0; 
int tempLen = 0; 
memset(tagCopy, 0, 256); 
memset(ret, 0, 128); 
pFile += ((int)*currentPos); 
while (totalLen+(*currentPos) < sizeSound) { 
    if (*pFile == '<') { 
     pFile += 5; 
     totalLen += 5; 
     while(*pFile != '>'){ 
      *tagCopy = *pFile; 
      tagCopy++; 
      pFile++; 
      totalLen++; 
      tempLen++; 
     } 
     tagCopy -= tempLen; 
     tempLen = 0; 
     if (strcmp(tagCopy, tag) == 0) { 
      pFile++; 
      totalLen++; 
      while (*pFile != '<') { 
       *ret = *pFile; 
       ret++; 
       pFile++; 
       totalLen++; 
       tempLen++; 
      } 
      ret -= tempLen; 
      *currentPos += totalLen; 
      tagCopy = NULL; 
      free(tagCopy); 
      return; 
     }else{ 
      memset(tagCopy, 0, 256); 
     } 
    } 
    pFile++; 
    totalLen++; 
} 
tagCopy = NULL; 
free(tagCopy); 
*currentPos = sizeSound; 
ret = NULL; 
} 

这显然给了我与“tagCopy”内存泄漏。 谁能告诉我为什么?我以为我有这个不错的,但这是唯一的地方,我得到一个内存泄漏。

谢谢。

回答

4

您在该例程中修改tagCopy几次,然后尝试稍后释放它。可能很危险。在调用free()之前,您还将tagCopy设置为NULL,因此每次尝试释放NULL而不是您分配的实际内存时。

+0

嗯,你有什么建议如何解决它? – funckymonk 2010-07-16 04:28:06

+2

说得好。最好使用数组语法('tagCopy [i]')或别名指针。修改'tagCopy'使其更难分析。 – 2010-07-16 04:28:17

+0

@funckymonk,马修有很好的建议。我会说1)不要麻烦将其设置为NULL,并且2)避免在例程中修改它(或者如果您愿意,可以保存原始指针的副本以便随后释放)。 – 2010-07-16 05:01:04

相关问题