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 use operator[]? e.g. using c_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(), returns data()[pos]. otherwise, if pos == 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) if pos < size(), otherwise reference object of type t value chart(); referenced value shall not modified.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

python 3.x - PyQt5 - Signal : pyqtSignal no method connect -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)