Log in

No account? Create an account

(no subject)

« previous entry | next entry »
Jan. 6th, 2006 | 11:06 am

#include <list>
#include <iostream>

int main()
  std::list::const_iterator i;
  i++; // I don't know why 1 increment is safe but two causes a segfault.
  std::cout << "i'm alive" << std::endl;

Under g++, the above code compiles without warnings with g++ -Wall, but when run segfaults. Is this a bug with the STL, or a bug in the compiler? It'd be nice if it either 1) didn't crash or 2) generated a warning about using an uninitialized variable.

Link | Leave a comment | Share

Comments {1}


(no subject)

from: nogbogfrog
date: Jan. 7th, 2006 08:39 am (UTC)

So the code above isn't quite right. list requires a template parameter, but I get your complaint. It's not a bug, because the const_iterator object is initialized via the default constructor. The fully explicit declaration is actually:

const_iterator i = const_iterator();

Thus, there is no warning about uninitialized values. I guess the proper thing to do is use an assert:

assert( i != NULL );

Now the issue of 2 increment calls before a crash can be construed as an STL bug. GNU C++, as of version 4.0, does not initialize the node pointer to NULL in the default ctor for list::const_iterator. If it had done that, then the very first call to i++ would have caused an access violation error.

Note that your code won't crash for a vector iterator. Since a vector is just an array, it calculates the addresses via pointer arithmetic. However the linked list and tree based containers will crash.


Reply | Thread