尽管释放分配的内存,但内存泄漏

时间:2014-12-03 18:05:59

标签: c++ memory-leaks valgrind

我有一个const char *,我需要用逗号分割。因为strtok会修改输入字符串,所以我会复制它,并在函数末尾释放已分配的内存。

void ApBuilder::addNetworkType(ApDbData::RowIterator &iter)
{
    const char * type = iter.getColumnText(ApDbData::AP_IDX_TYPE_80211);

    const size_t len = strlen(type);
    char * temp = new char[len +1];
    strncpy(temp, type, len);
    temp[len] = '\0';

    temp = strtok(temp, ",");

    while(temp != NULL)
    {
        tmpObject.add(temp, true);

        temp = strtok(NULL, ",");
    }

    jsonObject.add("type80211", tmpObject);

    delete[] temp;
}

Valgrind抱怨我尽管释放了已分配的内存但仍有内存泄漏。我该如何解决这个漏洞

==17667== 8 bytes in 2 blocks are definitely lost in loss record 1 of 4
==17667==    at 0x402ADFC: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==17667==    by 0x8049C5D: ApBuilder::addNetworkType(AbstractDbData::RowIterator&) (in /home/***/workspace/projects/jsonBuilder/main)
==17667==    by 0x8049A38: ApBuilder::buildApArray() (in /home/***/workspace/projects/jsonBuilder/main)
==17667==    by 0x8049679: main (in /home/***/workspace/projects/jsonBuilder/main)

3 个答案:

答案 0 :(得分:2)

strtok修改临时指针。您需要删除原始指针值。 (为此目的将其保存在变量中。)

答案 1 :(得分:1)

您需要将temp_ptr分配给strtok值。每次重新分配临时值时,您都会丢弃临时字符串的开头。

tok_ptr = strtok(temp, ",");

while(tok_ptr != NULL)
{

//你可能想在最后一个tok_ptr和下一个tok_prt之间添加子串         tmpObject.add(temp,true);

    tok_prt = strtok(NULL, ",");
}

答案 2 :(得分:0)

导致内存泄漏的问题正如ScottMcP-MVP所说的那样。

避免此类泄漏的c ++方法是使用众多std帮助程序之一: auto_ptr / unique_ptr,vector。为什么不是一个字符串?

std::string copy(iter.getColumnText(ApDbData::AP_IDX_TYPE_80211);
copy.append('\0');
char *temp = &copy[0];
temp = strtok(temp, ",");
....