Random Number Initialization

closed account (Lv0f92yv)
I am working on a linked list, and have the list working correctly. I am not modifying my Node class to generate a pseudo random key. After playing with the srand() parameter for initialization, I came up with this:

1
2
srand( time(NULL) + (int)&data );
key = rand();


(This is inside my Node constructor, which has access to a just-initialized 'data' field by a parameter passed in to constructor):

1
2
3
4
5
6
7
8
Node::Node(int val)
{
	data = val;
	next = NULL;
	prev = NULL;
	srand( time(NULL) + (int)&data );
	key = rand();
}


The address for the 'data' field seems different every time, and how randomly assigned is it? My understanding is that the OS deals with which memory to allow my program to allocate to 'data' in this case.

Thanks
Last edited on
common mistake.

Don't call srand before every call to rand.

You need to call srand exactly once in the entire lifetime of the program: when it first starts up.

1
2
3
4
5
6
// when your program starts up
srand( time(0) );

// when you need a random number
  // don't call srand!
key = rand();
closed account (Lv0f92yv)
Ahh yes.. I knew this, and thought nothing of it when I wrote that bit. Thanks.

As far as using the address of a variable assigned at runtime - does this enhance the randomness? I understand that a true random number is based on pure randomness (noise from a superconductor, keystrokes, interrupt threads?) etc. How about addresses of variables?
Last edited on
It won't help you really...if anything, it's probably not any more random than the current time.
closed account (Lv0f92yv)
Yea... I just experimented using srand(time(0)) in my main code, and it appears just as random. Thanks.
Topic archived. No new replies allowed.