c++ - Accessing null-termination character in std::string (string subscript out of range) -
consider following 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 expect program iterate on characters of string, reach null-terminating character breaking loop , reach program end correctly. however, when tried compiling in debug mode under visual studio 2010 reaching exception "string subscript out of range". when compiling in release mode program passes, bigger project depending on behaviour crashes - perhaps because of issue.
however, when checked specification of std::string::operator[]
@ www.cplusplus.com, end-character string handled explicitly:
if pos equal string length, function returns reference null character ('\0').
i ask here:
- is interpretation of specification of
std::string
correct? or missing something? - if problem lies on vs side of implementation, how can fix - without calling
length()
each time useoperator[]
? e.g. usingc_str()[i]
safe? - if problem lies on vs side of implementation - know if fixed in vs 2012 or pehaps fixed in future?
this 1 of things changed between c++03 , c++11.
it seems undefined behaviour in c++03:
21.3.4 basic_string element access [lib.string.access]
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
1 returns: if
pos < size()
, returnsdata()[pos]
. otherwise, ifpos == size()
,const version returns chart()
. otherwise, behavior undefined.
while in c++11, ok.
21.4.5 basic_string element access [string.access]
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
1 requires: pos <= size().
2 returns:
*(begin() + pos)
ifpos < size()
, otherwise reference object of typet
valuechart();
referenced value shall not modified.