http://gcc.gnu.org/bugzilla/show_bug.cgi?id=54523
Bug #: 54523 Summary: srand() initializing seed for random() function Classification: Unclassified Product: gcc Version: 4.4.6 Status: UNCONFIRMED Severity: normal Priority: P3 Component: libstdc++ AssignedTo: unassig...@gcc.gnu.org ReportedBy: jm3...@gmail.com DESCRIPTION: This problem arises if you mix the use of this two ways of generating random numbers: the srand()/rand() way and the srandom()/random() function family. The issue is that srand() is somehow initializing the seed for random() function, but it should be initialized *only* with srandom(). The expected behavior is random() generator not modifying its seed until done by srandom(), the current behavior is srand() changing that seed. IMPACT: As happened to me with a scientific code, it could imply a portability problem as this is working properly (from my humble point of view) in other implementations of the library. I detected (and just reported) also the problem in GNU implementation of glibc 2.12 with C. HOW TO REPRODUCE: This is a short test program, rndtest.cpp: ---- START SOURCE CODE ---- // Test random() #include <iostream> #include <cstdlib> using namespace std; int main() { int i; srand((unsigned)time(NULL)); for (i=1;i<11;i++) { cout << (random() / (double)0x7fffffff) << endl; } } ---- SOURCE CODE END ---- This is what you get with libstdc++-devel-4.4.6: $ g++ -O0 -g -Wall rndtest.cpp -o rndtest $ ./rndtest 0.735861 0.130081 0.954666 0.622049 0.423014 0.0441652 0.855401 0.895524 0.178504 0.758294 $ ./rndtest 0.599818 0.550412 0.763289 0.448671 0.365695 0.772274 0.224044 0.700837 0.492885 0.85191 This is the expected (what you get in the mentioned other implementation of cstdlib): > ./rndtest 0.840188 0.394383 0.783099 0.79844 0.911647 0.197551 0.335223 0.76823 0.277775 0.55397 > ./rndtest 0.840188 0.394383 0.783099 0.79844 0.911647 0.197551 0.335223 0.76823 0.277775 0.55397 Many thanks.