views:

191

answers:

3

The code below compiled in Debug configuration in VS2005 SP1 shows two messages with “ITERATOR LIST CORRUPTED” notice.

Code Snippet

#define _SECURE_SCL 0
#define _HAS_ITERATOR_DEBUGGING 0

#include <sstream>
#include <string>

int main()
{
  std::stringstream stream;
  stream << "123" << std::endl;
  std::string str = stream.str();
  std::string::const_iterator itFirst = str.begin();
  int position = str.find('2');
  std::string::const_iterator itSecond = itFirst + position;
  std::string tempStr(itFirst,itSecond); ///< errors are here
  return 0;
}

Is it a bug in the compiler or standard library?

+3  A: 

My bad! Edit: Yeah problem with compiler. See this -- particularly the Community Content section.

dirkgently
What do you mean? `std::string` does have random-access iterators.
avakar
why is the code compileable than?
Vlad
+1  A: 

What @dirkgently said in his edit.

Apparently, some code for std::string is located in the runtime dll, in particular the macro definition does not take effect for the constructor an the code for iterator debugging gets executed. You can fix this by linking the runtime library statically.

I would consider this a bug, though perhaps not in the Visual Studio itself, but in the documentation.

avakar
Thank you. Linking statically solves the problem.
Konstantin
A: 

There is a problem with your code. Well, several in fact:

  1. std.find('2') returns a size_t, you have a potential cast problem if the value of the size_t returned (like std::string::npos) is superior to what an int can hold (you would end up with a negative int I think...)
  2. if position is negative, or equal to std::string::npos then the range itFirst,itSecond is ill-defined (either because itSecond is before itFirst or because it is past str.end())

Correct your code, and check if it stills throw. Iterator Debugging is here to help you catch these mistakes, disabling it acting like an ostrich.

Matthieu M.
The string version of find() actually returns a std::string::size_type.
anon
Generally you are right, but in this specific case `_HAS_ITERATOR_DEBUGGING` is switched off. If you set `_HAS_ITERATOR_DEBUGGING` to 1 there will be no errors. Thus, seems to be a bug in CRT.
Paul
@Neil: true, and most containers effectively use an inner typedef `size_type` for all indexing purpose, which I have never seen being other than `size_t` in the (few) implementations of the STL I have come upon. The real problem is that most often that not it's an unsigned value (since indexing in negative does not make sense, unless you are using sweet Python).
Matthieu M.