为什么这个字符串会搜索并替换segfault?

发布于 2024-10-10 13:46:12 字数 583 浏览 0 评论 0原文

colours 是一个 std::map,其中每对的第一个元素是 2 个字母的 std::string 颜色代码,第二个元素是该颜色的 7 个字符 std::string shell 转义代码。

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);
    }
}

运行此代码时,程序会出现段错误。我最好的猜测是,这与替换字符串的长度比它要替换的字符串的长度长有关,但据我所知,这只会导致 char * 出现段错误,而不是 std::string

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

混浊又暗下来 2024-10-17 13:46:12

string::replace 采用起始位置和长度,而不是起始位置和结束位置。此外,sizeof 不返回字符串的长度。因此,第三行可能应该是这样的:

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

对于它的价值,sizeof 返回对象消耗的堆栈空间量,这在编译时是已知的。因此,它不能随调用而变化,而字符串的长度却如此。

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.

彩虹直至黑白 2024-10-17 13:46:12

@luqui 已经回答了为什么它会出现段错误,但我想添加其他内容。

如果替换字符串包含搜索字符串,请小心不要陷入无限循环。您可以通过传递 string::find() 开始搜索的位置来避免这种情况。这也将提高效率,因为当前的解决方案可能会退化为 O(N2)。

@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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文