简体   繁体   English

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

[英]Memory leak despite freeing allocated memory

I have a const char * that I need to split by comma. 我有一个const char *,我需要用逗号分隔。 Because strtok modifies the input string I make a copy of it, and free the allocated memory at the end of the function. 因为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 complains that I have a memory leak despite my freeing of the allocated memory. 尽管我释放了分配的内存,但Valgrind抱怨说我有内存泄漏。 How do I fix this leak 我该如何解决这个漏洞

==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)

strtok modifies the temp pointer. strtok修改临时指针。 You need to delete the original pointer value. 您需要删除原始指针值。 (Save it in a variable for this purpose.) (为此目的将其保存在变量中。)

You need to assign a temp_ptr to the strtok value. 您需要将temp_ptr分配给strtok值。 You're discarding the start of the temp string everytime you reassign temp. 每次重新分配temp时,都会丢弃临时字符串的开头。

tok_ptr = strtok(temp, ",");

while(tok_ptr != NULL)
{

//You probably want to add the substring between the last tok_ptr and next tok_prt tmpObject.add(temp, true); //你可能想在最后一个tok_ptr和下一个tok_prt tmpObject.add(temp,true)之间添加子串;

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

The problem leading to the memory leak is strtok as ScottMcP-MVP said. ScottMcP-MVP表示,导致内存泄漏的问题非常严重。

The c++ way to avoid leaks of this kind would be to use one of the many std helpers: auto_ptr/unique_ptr, vector. 避免这种泄漏的c ++方法是使用许多std帮助程序之一:auto_ptr / unique_ptr,vector。 Why not a string? 为什么不是字符串?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM