Mat*_*Man 3 c++ string iterator insert segmentation-fault
码:
#include <iostream>
#include <string>
using namespace std;
string expand(string mask);
int main()
{
string tiny = "blah blah [a-e] blah blah";
string lengthy = "blah blah [a-i] blah blah";
cout << expand(tiny) << endl;
cout << expand(lengthy) << endl;
return 0;
}
string expand(string mask)
{
int i, range;
/* find the first bracket, grab start letter */
unsigned int bracket = mask.find("[");
char start = mask[bracket + 1];
/* point iterator at first bracket */
string::iterator here = mask.begin();
here += bracket;
/* find second bracket, calculate ascii range */
range = mask[bracket + 3] - mask[bracket + 1];
/* kill brackets and their contents*/
mask.erase(here, here + 5);
/*** This loop causes an error on the 7th iteration ****/
for(i = 0; i <= range; i++)
mask.insert(here, (start + range) - i);
return mask;
}
Run Code Online (Sandbox Code Playgroud)
输出:
matt @ Callandor:〜/ prog/tempVer $ g ++ test.cpp -o play
matt @ Callandor:〜/ prog/tempVer $ ./play
等等等等等等
blahblah defghi blah blah
*检测到glibc* ./play:free():下一个大小无效(快速):0x08353068
======= Backtrace:========= /lib/libc.so.6(+0x6c501)[0x5b5501] ...
尝试使用string :: insert(iterator,char)时,我遇到了一些奇怪的行为; 我把它放在'for'循环中,我根本不移动迭代器,循环只是插入字符.如果我有六个或更少的字符要插入,它可以正常工作,但七个或更多的失败.
根据输出(见上文),看起来在六次插入后,迭代器跳转到字符串的开头并开始插入垃圾.当程序结束时,我得到一个大的混乱错误.
在尝试隔离原因时,我尝试了两个循环(没有一个触及迭代器):
for(i = 0; i < 6; i++)
mask.insert(here, (start + range) - i);
cout << mask << endl;
for(i = 0; i < 7; i++)
mask.insert(here, (start + range) - i);
cout << mask << endl;
Run Code Online (Sandbox Code Playgroud)
第一次完成就好了,第二次造成了分段错误.
谁知道这里发生了什么?
在倾注您的代码之后,我注意到您使用的是无效的迭代器.
简而言之,插入字符串会使其迭代器无效.插入之后,here迭代器不再有效,因为在其他实现特定的细节中,字符串容量可能会增加.当here插入后再次使用迭代器时,这会导致未定义的行为,而不会先将其重置为已修改字符串中的有效位.