Sunday, 18 August 2013

Accessing null-termination character in std::string (string subscript out of range)

Accessing null-termination character in std::string (string subscript out
of range)

Consider the following very simple text example:
#include <stdio.h>
#include <string>
int main() {
std::string x("ugabuga");
int i=0;
while (x[i]) {
++i;
}
printf("%d\n",i); //should print 7
return 0;
}
I would expect the program to iterate over all characters of the string,
then reach the null-terminating character breaking the loop and reach the
program end correctly. However, when I tried compiling it in debug mode
under Visual Studio 2010 I am reaching an exception "string subscript out
of range". When compiling in release mode this program passes, but my
bigger project depending on this behaviour crashes - perhaps because of
this issue.
However, when I checked the specification of std::string::operator[] at
http://www.cplusplus.com/reference/string/string/operator%5B%5D/, the
end-character string is handled explicitly:
If pos is equal to the string length, the function returns a reference to
a null character ('\0').
I would like to ask here:
Is my interpretation of specification of std::string correct? Or am I
missing something?
If the problem lies on VS side of implementation, how can I easily fix
this - hopefully without calling length() each time I use the operator[]?
e.g. will using c_str()[i] will be safe?
If the problem lies on VS side of implementation - do you know if it is
fixed in VS 2012 or pehaps will be fixed in the future?

No comments:

Post a Comment