【问题标题】:ipad, Need help with a memory leakipad,需要帮助解决内存泄漏问题
【发布时间】:2010-07-16 04:13:20
【问题描述】:

我有这个代码:

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”的内存泄漏。 谁能告诉我为什么?我以为我把它写得很好,但这是我唯一出现内存泄漏的地方。

谢谢。

【问题讨论】:

    标签: c ipad memory-leaks


    【解决方案1】:

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

    【讨论】:

    • hmm,您对如何修复它有什么建议吗?
    • 说得好。最好使用数组语法 (tagCopy[i]) 或别名指针。修改tagCopy 会更难分析。
    • @funckymonk,马修有很好的建议。我想说 1) 永远不要将其设置为 NULL,并且 2) 避免在例程中修改它(或者如果您愿意,可以保存原始指针的副本以供以后释放)。
    • @Carl Norum - 在释放后将指针设置为 NULL 是一个好习惯。不是吗?
    • ...尤其是在之前释放它。
    猜你喜欢
    • 2011-08-07
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2011-03-27
    • 2012-07-15
    相关资源
    最近更新 更多