...
Code Block |
---|
char input[] = "bogus@addr.com; cat /etc/passwd"; string::iterator loc; string email; // 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; } // end string for each element in NTBS |
Non-Compliant Example
In this non-compliant example, the string s} is initialized as "rcs" and the {{string iterator si
is initialized to the beginning of the string. The size of s
is three, and we'll assume the capacity is fifteen. The for
loop appends 20 characters to the end of the sting. As a result, the si
iterator is invalided because the capacity of the string is exceeded requiring a reallocation. As a result, the call to insert()
results in undefined behavior.
Code Block |
---|
string s("rcs"); string::iterator si = s.begin(); // add 20 'x' chars to end of string for (size_t i=0; i<20; ++i) { s.push_back('x'); } s.insert(si, '*'); |
Compliant Solution
The relationship between size and capacity makes it possible to predict when a call to a non-const member function will cause a string
to perform a reallocation. This in turn makes it possible to predice when an insertion will invalidate references, pointers, and iterators (to anything other than the end of the string).
In the following examplethis compliant solution, the non-compliant example is modified to only append capacity - size characters to the string s
. As a result, the call to push_back()
does not invalidate no longer invalidates the iterator.
Code Block |
---|
string s("rcs"); ... string::iterator si = s.begin(); for (size_t i=0; i < 20; ++i) { if ( s.size() <== s.capacity() ) { break; } s.push_back('x'); } s.insert(si, '*'); |
If instead of performing a push_back()
, the code were to insert into an arbitrary location in the string, all references, pointers, and iterators from the insertion point to the end of the string are invalidated.
...