Thread: Bus Error (rand)

  1. #1
    Registered User
    Join Date
    Nov 2006
    Location
    japan
    Posts
    126

    Angry 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.

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    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 *?

  3. #3
    Registered User
    Join Date
    Nov 2006
    Location
    japan
    Posts
    126
    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?

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    The code segment you showed is not causing the crash then.

  5. #5
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    Code:
    srand ( time(NULL) );
    ssharish2005

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. SM Bus
    By yanol in forum C++ Programming
    Replies: 3
    Last Post: 06-04-2008, 10:02 AM
  2. Trying to generate a bus error
    By Tommo in forum C Programming
    Replies: 4
    Last Post: 08-22-2007, 05:37 AM
  3. sem_init -> bus error
    By g_p in forum C Programming
    Replies: 4
    Last Post: 12-03-2006, 12:14 PM
  4. Initializing array of structures causing bus error
    By Aaron M in forum C Programming
    Replies: 5
    Last Post: 03-05-2006, 01:40 AM
  5. Replies: 72
    Last Post: 11-25-2002, 05:55 PM