Puppy
Puppy

Reputation: 146910

Having trouble with a memory leak - rebinding keys in std::map

void filename_changed(string originalfilename, string newfilename) {
    auto it = file_source_map.find(originalfilename);
    if (it == file_source_map.end())
        return;
    file_source_map.insert(std::pair<const string, string>(newfilename, it->second));
    file_source_map.erase(originalfilename);
}

I replaced the allocators of std::map and std::string, so I know for certain that this is leaking memory, but I can't see the issue. If originalfilename exists in the map, insert it's value at newfilename, and erase originalfilename.

Upvotes: 2

Views: 564

Answers (2)

Naveen
Naveen

Reputation: 4678

Since keys are unique in std::map, Shouldn't you erase the old key, value and then insert the new key,value?

Upvotes: 0

stefaanv
stefaanv

Reputation: 14392

Except for the simpler (probably replaced while investigating the memory leak)

file_source_map.insert(std::make_pair(newfilename, it->second));
file_source_map.erase(it);

and a check that both filenames are not the same (which would not leak, but actually erase the entry), there is nothing obvious wrong with the code.

Check other things (like the allocators?).

Upvotes: 2

Related Questions