开发者

Why does this string search and replace segfault?

colours is a std::map<string, string> where the first element of each pair is a 2 letter std::string colour code, and the second element is the 7 character std::string shell escape code for that colour.

size_t i;
for(map<string, string>::iterato开发者_如何转开发r iter = colours.begin(); iter != colours.end(); iter++) {
    while((i = text.find(iter->first)) != string::npos) {
        text.replace(i, i + sizeof(iter->first), iter->second);
    }
}

When this code is run, the program segfaults. My best guess is that it is something to do with the length of the replacement string being longer than the length of the string it's replacing, but to the best of my knowledge that can only cause segfaults with char *, not std::string.


string::replace takes a start position and a length, not a start position and an end position. Also sizeof does not return the length of a string. So the third line should probably read:

text.replace(i, iter->first.length(), iter->second);

For what it's worth, sizeof returns the amount of stack space consumed by the object, which is known at compile time. So it cannot vary from call to call, which the string's length does.


@luqui already answered why it segfaults, but I wanted to add something else.

Be careful not to end up in an infinite loop in the case where you your replacement string contains the search string. You can avoid this by passing string::find() a position to start searching. This will also improve efficiency as your current solution could degenerate to O(N2).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜