This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

std::list iterator not dereferencable


Hi,

Today, I tried to build some Linux application using VC++ 7.1/8.0
and I encountered strange GCC 3.2.3 behaviour that make me thinking
about possible bug in GCC (or libstdc++, I'm not sure).

Here is small function:

list<int> foo()
{
   list<int> col;
   col.push_back(2); // dummy data
   return col;
}

Here is code snippet using this foo():

std::list<int>::iterator it = foo().begin(); // <--- [1]
int data = *it; // <--- [2]


>From the first glance, this code seems to be valid
but certainly it isn't.
[1] std::list<int> returned from foo() lives *only* untill the end of
the full expression, semicolon. This list is not available
in the line [2], so iterator is invalid and undefined behaviour occurs.
That is how I understand explanation in the chapter "12.2 Temporary
objects" of C++ Standard:

"Temporary objects are destroyed as the last step in evaluating the
full-expression (1.9) that (lexically) contains the point where they
were created."


Now, when I try to build it with GCC 2.3.2 and run, everything
works well:

[mloskot@wl ~/tmp]$ g++ -Wall -pedantic-errors -ansi list.cpp
[mloskot@wl ~/tmp]$ ./a.out
2
[mloskot@wl ~/tmp]$

But, when I try to compile it using VC++ 7.1 or 8.0
the program crashes in the line [2] and I got error message about "list
iterator not dereferencable".

The strange thing is that I also tested this behaviour
with VC++ 7.1 + STLport 5.0 and it does not cause any crash,
similarly to the case with GCC.

Summary:
--------


What I'm sure in this case is:

- following usage of foo() causes undefined behaviour

std::list<int>::iterator it = foo().begin(); // <--- [1]
int data = *it; // <--- [2]

- correct usage may look as follows

std::list<int> a = foo();
std::list<int>::iterator it = a.begin();
int data = *it; // here 'a' object is still alive


Also, I understand what C++ Standard says about temporary objects.
I hope so :-)


But my question is why GCC 3.2.3 compiles this code and it runs well?
Does it mean there is a bug in GCC or may be in libstdc++ implementation?

Thanks in advance for any comments.

Best regards
-- 
Mateusz Åoskot
http://mateusz.loskot.net


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]