Hacking - The Art of Exploitation, 2nd Edition

(Romina) #1
Programming 101

function_ptr is 0x0804838d
This is function two
value returned was 2
reader@hacking:~/booksrc $


0x286 Pseudo-random Numbers


Since computers are deterministic machines, it is impossible for them to


produce truly random numbers. But many applications require some form of


randomness. The pseudo-random number generator functions fill this need


by generating a stream of numbers that is pseudo-random. These functions


can produce a seemingly random sequence of numbers started from a seed


number; however, the same exact sequence can be generated again with the


same seed. Deterministic machines cannot produce true randomness, but if


the seed value of the pseudo-random generation function isn’t known, the


sequence will seem random. The generator must be seeded with a value


using the function srand(), and from that point on, the function rand() will


return a pseudo-random number from 0 to RAND_MAX. These functions and


RAND_MAX are defined in stdlib.h. While the numbers rand() returns will appear


to be random, they are dependent on the seed value provided to srand().


To maintain pseudo-randomness between subsequent program executions,


the randomizer must be seeded with a different value each time. One common


practice is to use the number of seconds since epoch (returned from the time()


function) as the seed. The rand_example.c program demonstrates this


technique.


rand_example.c


#include <stdio.h>
#include <stdlib.h>


int main() {
int i;
printf("RAND_MAX is %u\n", RAND_MAX);
srand(time(0));


printf("random values from 0 to RAND_MAX\n");
for(i=0; i < 8; i++)
printf("%d\n", rand());
printf("random values from 1 to 20\n");
for(i=0; i < 8; i++)
printf("%d\n", (rand()%20)+1);
}


Notice how the modulus operator is used to obtain random values from


1 to 20.


reader@hacking:~/booksrc $ gcc rand_example.c
reader@hacking:~/booksrc $ ./a.out
RAND_MAX is 2147483647
random values from 0 to RAND_MAX

Free download pdf