Somewhere in one book I was reading about secure coding in C++ with std::string:
So I came across one example given below:
1 2 3 4 5 6 7 8 9 10
char input[];
string::iterator loc = email.begin();
//copy into string converting ";" to " "
for(size_t i=0; i<strlen(input); i++)
{
if(input[i] != ';')
email.insert(loc++, input[i]);
else
email.insert(loc++, ' ');
}
Then it saying:
"The problem with this code is that the iterator loc is invalidated after the first call to insert(), nad
every subsequent call to insert() result in undefined behavior."
This problem can esily repaired:
1 2 3 4 5 6 7 8 9 10 11
char input[];
string::iterator loc = email.begin();
//copy into string converting ";" to " "
for(size_t i=0; i<strlen(input); ++i)
{
if(input[i] != ';')
loc = email.insert(loc, input[i]);
else
loc = email.insert(loc, ' ');
++loc;
}
I am not getting what was the problem and how it resolved?
Can anyone please explain?
An iterator can be considered a pointer to a certain element in the container. When a string container adds an element it is likely that the underlying buffer is destroyed and a new larger buffer is created. The iterator that pointed to the element in the old buffer will then be invalid and you need one to the newly created buffer (this is what insert returns).