std::string

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?

-Thank You
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).
Thank you very much. This is very helpful.
> Then it saying: "The problem with this code is that the iterator loc is invalidated ...

The fundamental problem with the code is that it is badly written.

> This problem can esily repaired

This too is bad code; cnsider throwing this book away.

This would be a sane way of doing it:
1
2
3
4
5
extern char input[];

// copy input into string email converting ";" to " "
std::string email = input ;
for( char& c : email ) if( c == ';' ) c = ' ' ;


This would be another (which may be favoured by programmers with a strong C bias):
1
2
3
4
5
6
extern char input[];

// copy input into string email converting ";" to " "
std::string email ;
for( const char* p = input ; *p != 0 ; ++p ) 
    if( *p  == ';' ) email += ' ' ; else email += *p ;
Thanks JLBorges :)

Actually, you are right that this is an example of very bad code and the book is saying the same :
"Example of bad code security point of view".
Topic archived. No new replies allowed.