I want to create a program which only needs one random number, so I try to use the address of argc in main function as random source because I think the location of the program in memory is random, and also it can save some include statements, so I tried:
#include <stdio.h>
int main(int argc,const char* argv[]){
printf("%lu\n",(unsigned long int)&argv/sizeof(unsigned long int));
return 0;
}
but I found the output at each time is not very "random": they are multiples of 4:
17591828907268
17591841542404
17591845040388
17591834556676
What is the reason? And is using address of argc as random number possible?
Then I try remove some bits of the address:
#include <stdio.h>
int main(int argc,const char* argv[]){
printf("%lu\n",(unsigned long int)&argv >> 12);
return 0;
}
it looks quite random this time, at least it has both odd and even numbers:
34359070631
34359034616
34359078055
34359080624
is that "correct" way to turn the address of argc into random number?
What is the reason?
Alignment requirements for your architecture, which I assume is x86 and int
is 4 bytes, which means each int
should be aligned to an address that is divisible by 4 (which is exactly the behavior you're seeing).
And is using address of argc as random number possible?
Possible? Yeah, sure. You just go ahead and do it.
Is it a good idea? No, definitely not. See below for why.
Is that "correct" way to turn the address of argc into random number?
I assume by "correct" you mean a good source of entropy, and the answer to that is no.
There is some degree of address space layout randomization in modern operating systems, but it's not meant to be a good source of entropy. It's just meant to make it harder for someone to use a bug in your program as a security exploit. And there really aren't any guarantees about ASLR (you can turn it off in some operating systems if you really wanted to).
In short, you should not use the address of a variable as your source for entropy. It's just not a good source of randomness.
If you really need randomness, you should use one of:
/dev/urandom
For info on these two, see How to use /dev/random or urandom in C?
srand()
Info on seeding srand() is here: Recommended way to initialize srand?
An external library specifically designed for it.
Some info here A good random number generator for C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With