random_range

Posted by Zeno on Thu 23 Jun 2005 06:13 PM — 7 posts, 17,510 views.

USA #0
I'm using SocketMUD and I seem to be having an issue with random_range. It crashes:
(gdb) f 4
#4  0x0804fe46 in pre_battle (acct=0xbfffe680, arg=0x80512b8 "") at battle.c:259
259        sprintf ( buf3, "Interesting fact #%d: %s", number+1, fact_table[number].text );
(gdb) p number
$1 = 544501582


   number = random_range( 0, MAX_FACTS);

   sprintf ( buf3, "Interesting fact #%d: %s", number+1, fact_table[number].text );
   communicate(acct, buf3, COMM_INFO);



#define MAX_FACTS 5


I have no idea why number is that high. It shouldn't go past 5.

/* returns a random number between a and b */
int random_range(int a, int b)
{
  return ((int)(rand_seed() * ((double) (b) - (a) + 1))) + (a);
}


The whole random.c file can be found here:
http://www.daimi.au.dk/~jobo/socketmud/download/snippets/random.tar.gz

Anyone know why it's such a high number? My fact_table has 5 facts so it should go up to only 5.

This doesn't happen everytime. About 1 in 10 times.
Amended on Thu 23 Jun 2005 06:39 PM by Zeno
USA #1
There could be a bug in the random number generation code or you misusing it somehow. Are you initializing it using its init functions?

If you write a for loop in a separate program printing out 100 random numbers between 0 and 5, are they all between 0 and 5?
USA #2
Well there's never been a problem with it before. I used it for a damage function. It always did the range.

  dam = random_range( 1, 5 );


I tested this just now. It never did anything outside of 1 - 5.
USA #3
Well, if the function works and you know it works, there must be a problem in your code somewhere. A stack overflow that's corrupting memory, a bad type that's causing overflow, who knows.

I'd still recommend however that you write a for loop to exactly replicate your situation that is random_range(0, 5).

I'd also recommend actually stepping through the function in question and seeing if values are sane all the way through.
USA #4
Well this is odd.
(gdb)
259        number = random_range( 0, MAX_FACTS);
(gdb) p number
$5 = 134586728
(gdb) next
261        sprintf ( buf3, "Interesting fact #%d: %s", number+1, fact_table[number].text );
(gdb) p number
$7 = 4


Did I print number before it was set the first time?
USA #5
Yes. When it shows you a statement, that's what it's about to execute, so printing out 'number' will give you the previous (uninitialized) value.
USA #6
Okay that's what I thought. I'll check more later into this with gdb and step after work.