-
Bus Error (rand)
Hello
I wrote a function that generates 10 000 times a pair of different random numbers,
but somethimes i got bus errors.
(with out compiling twice, sometimes bus error, sometimes ok.... )
is the first time I got that time of errors..., it only appears sometimes, not always.
Does it have any relation with the number of iterations??
or something with time.h? or srand()? or rand?
here is part of my function.
Code:
unsigned long int iter=10000;
int seg1, seg2;
srand((unsigned int)time((time_t *)NULL));
for(i=0;i<iter;i++){
seg1=rand()%(nNodes-1);
do {seg2=rand()%(nNodes-1);}while(seg2==seg1);
/*make calculations... */
}
does it make any change if i put srand inside the for loop?
help please!...
thanks in advance.
-
As a general rule, call srand() only once.
If nNodes is ever 1, you'll end up dividing by 0. That's one way to crash.
Incidentally, why the heck are you casting NULL to time _t *?
-
first, nNodes is defined as 21 ( I forgot to say it, sorry)
second:
Regarding to casting NULL I don't usually use random number so i just copied it from somewhere.
is there any better way to use srand?
-
The code segment you showed is not causing the crash then.
-
Code:
srand ( time(NULL) );
ssharish2005