Reputation: 899
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>::iterator 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
.
Upvotes: 0
Views: 438
Reputation: 138417
@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).
Upvotes: 1
Reputation: 60503
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.
Upvotes: 6