简体   繁体   中英

Memory leak despite freeing allocated memory

I have a const char * that I need to split by comma. Because strtok modifies the input string I make a copy of it, and free the allocated memory at the end of the function.

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. 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. 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. You're discarding the start of the temp string everytime you reassign 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_prt = strtok(NULL, ",");
}

The problem leading to the memory leak is strtok as ScottMcP-MVP said.

The c++ way to avoid leaks of this kind would be to use one of the many std helpers: 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, ",");
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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