This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
gcc 4.0.2 bug report
- From: Stephan dot Beal dot extern at HVBInfo dot com
- To: gcc-bugs at gcc dot gnu dot org
- Date: Mon, 23 Jan 2006 15:23:43 +0100
- Subject: gcc 4.0.2 bug report
Hi, gcc team!
i unfortunately cannot use the bug db for this report because i am not
allowed to use this email address for websites, mailing lists, etc.
Bug summary: The two-arg form of std::random_shuffle() shuffles predictably
unless srand() is called beforehand.
GCC version:
gcc (GCC) 4.0.2
Copyright (C) 2005 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// ---------------------------------------------------------
// Begin source code:
#include <string> // std::string
#include <vector> // std::string
#include <iostream> // cout/cerr
#include <iterator>
#include <algorithm> // cout/cerr
#include <stdlib.h> // rand(), srand()
#include <time.h> // time()
int main( int argc, char **argv )
{
//srand(time(NULL));
// ACHTUNG: if srand() is not called then random_shuffle() always
// shuffles with the same results. This is undocumented behaviour
// and is probably limited to the GNU/GCC STL implementation.
// No STL documentation i have ever read (or can find at the moment)
// calls for explicitely seeding the RNG used by random_shuffle().
typedef std::vector<std::string> SVec;
SVec vec;
std::string line;
while( std::getline( std::cin, line ) ) {
vec.push_back( line );
}
std::random_shuffle( vec.begin(), vec.end() );
std::copy( vec.begin(), vec.end(),
std::ostream_iterator<std::string>( std::cout, "\n" ) );
return 0;
}
//----------------------------------------------------------
//end source code
Compile with:
gcc -o shuffle shuffle.cpp -lstdc++
Reproducing the behaviour:
Run on any list of input (e.g., a file with the numbers 1..5, one
number
per line), and repeat this any number of times. The results of the shuffling
will always be the same. e.g.: Input file 'foo' contains the letters "d c b
a",
one per line and in that order:
for i in 1 1 1 1 1; do ./shuffle < foo; sleep 1; done
d
a
c
b
d
a
c
b
d
a
c
b
d
a
c
b
d
a
c
b
Workaround: If the srand() line is uncommented, random_shuffle() shuffles
unpredictably (as
it should).
i have not found any STL documentation stating that the underlying system
RNG must be seeded
before using random_shuffle(), and can also find no examples on the web
demonstrating that it
should/must be seeded for proper operation. IMO this places an unwarranted
(and certainly
undocumented) expectation on the user.
Take care,
----- stephan beal