all. I’m working on software to block ads using the system’s hosts file, but on to the code.
I have a custom class HostEntry that contains necessary information such as the destination host, the host to block, the destination host’s ip… etc.
In the HostsManager class, it keeps a vector to keep track of all the hosts added. In order to block a host completely, I must add example.com AND www.example.com, but when I iterate over the vector it will only delete the entry starting with “www.” and leaves the one without. If you try to delete it a second time (with only the entry missing the “www.”) it segfaults, and I don’t know why.
void HostsManager::delHost(std::string blockedhost) {
strip(blockedhost);
string tmp; // yes I know it's not great practice to do it like this, but it was for debug reasons
for (vector<HostEntry>::iterator viter = hosts.begin(); viter != hosts.end(); ++viter) {
tmp = viter->getHost();
if (tmp == blockedhost || tmp == ("www." + blockedhost)) {
viter = hosts.erase(viter);
}
}
}
An example call to that specific function:
HostsManager mgr;
mgr.delHost("mysite.com"); // this deletes "www.mysite.com" but not "mysite.com" - whether or not you call delHost() with the "www." prefix
mgr.delHost("mysite.com"); // if you call it a second time, it segfaults O.o
Help with this would be GREATLY appreciated.
EDIT: I assigned the value returned from the call to erase() to viter, same result. I still have no idea why this is happening.
If you need all the code, it’s at http://paste.pocoo.org/show/363051/
It is generally better to use
std::remove_ifto delete multiple items from a vector; it runs in linear time instead of quadratic and avoids having to worry about iterator invalidation.Might look something like this:
You can accomplish a similar thing without C++0x lambdas via a struct to compare with: