> Just occurred to me a brilliant way to grab random values,
You sound like a noob who just "discovered" bubble sorting and thinks it's the most awesome thing they've ever seen.
> I've tested a few times just now and it seems to be a usable option even for security, at least to me anyways:
I wouldn't use this for a student dice rolling program, never mind for any serious statistical or security application.
The algorithm (such as it is), is painfully slow as well as being singularly useless.
Diehard tests - Wikipedia
On my machine, malloc() returns the same pointer every time, and time() is a constant.
clock() is barely able to do any better than being an incrementing counter.
Code:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<stddef.h>
#include<limits.h>
typedef ptrdiff_t mcc_rnd_t;
long mcc_rnd( mcc_rnd_t *seed, long min, long max ) {
unsigned char *tmp = malloc(1);
/* Initial random value */
long val = time(NULL) + ((ptrdiff_t)tmp);
if ( !seed ) seed = (mcc_rnd_t*)(&seed);
if ( *seed == 0 ) *seed = 1;
val %= *seed;
val *= clock();
free(tmp);
*seed <<= 1;
return (val > max) ? max : (val < min ? min : val);
}
void t1() {
printf("100 Clocks()\n");
long tests[100];
for ( int i = 0; i < 100; ++i ) {
tests[i] = clock();
}
for ( int i = 0; i < 100; ++i ) {
(void)printf( "%ld\n", tests[i] );
}
}
void t2() {
printf("100 times()\n");
long tests[100];
for ( int i = 0; i < 100; ++i ) {
tests[i] = time(NULL);
}
for ( int i = 0; i < 100; ++i ) {
(void)printf( "%ld\n", tests[i] );
}
}
void t3() {
printf("100 pointers()\n");
void *tests[100];
for ( int i = 0; i < 100; ++i ) {
tests[i] = malloc(1);
free(tests[i]);
}
for ( int i = 0; i < 100; ++i ) {
(void)printf( "%p\n", tests[i] );
}
}
int main() {
int i;
long seed = 1;
long tests[100];
t1();
t2();
t3();
for ( i = 0; i < 100; ++i ) {
tests[i] = mcc_rnd( &seed, LONG_MIN,LONG_MAX);
}
for ( i = 0; i < 100; ++i ) {
(void)printf( "%ld\n", tests[i] );
}
int dice[6] = { 0 };
for ( int i = 0 ; i < 60000000 ; i++ ) {
int d = mcc_rnd( &seed, LONG_MIN,LONG_MAX) % 6;
dice[d]++;
}
for ( int i = 0 ; i < 6 ; i++ ) {
printf("%d: %d\n", i, dice[i]);
}
}
Your 'distribution' is awful. Your online casino operator is now suing you.
Code:
0: 25929392
1: 3481475
2: 9589231
3: 7932192
4: 9587561
5: 3480149
real 0m21.880s
user 0m7.460s
sys 0m14.416s
Compare with calling rand() millions of times.
Much better, and MUCH quicker!.
Code:
0: 9998142
1: 9999581
2: 10000326
3: 10003300
4: 9997641
5: 10001010
real 0m0.600s
user 0m0.596s
sys 0m0.000s