26.07.2018 Views

hacking-the-art-of-exploitation

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

function_ptr is 0x0804838d<br />

This is function two<br />

value returned was 2<br />

reader@<strong>hacking</strong>:~/booksrc $<br />

0x286<br />

Pseudo-random Numbers<br />

Since computers are deterministic machines, it is impossible for <strong>the</strong>m to<br />

produce truly random numbers. But many applications require some form <strong>of</strong><br />

randomness. The pseudo-random number generator functions fill this need<br />

by generating a stream <strong>of</strong> numbers that is pseudo-random. These functions<br />

can produce a seemingly random sequence <strong>of</strong> numbers st<strong>art</strong>ed from a seed<br />

number; however, <strong>the</strong> same exact sequence can be generated again with <strong>the</strong><br />

same seed. Deterministic machines cannot produce true randomness, but if<br />

<strong>the</strong> seed value <strong>of</strong> <strong>the</strong> pseudo-random generation function isn’t known, <strong>the</strong><br />

sequence will seem random. The generator must be seeded with a value<br />

using <strong>the</strong> function srand(), and from that point on, <strong>the</strong> function rand() will<br />

return a pseudo-random number from 0 to RAND_MAX. These functions and<br />

RAND_MAX are defined in stdlib.h. While <strong>the</strong> numbers rand() returns will appear<br />

to be random, <strong>the</strong>y are dependent on <strong>the</strong> seed value provided to srand().<br />

To maintain pseudo-randomness between subsequent program executions,<br />

<strong>the</strong> randomizer must be seeded with a different value each time. One common<br />

practice is to use <strong>the</strong> number <strong>of</strong> seconds since epoch (returned from <strong>the</strong> time()<br />

function) as <strong>the</strong> seed. The rand_example.c program demonstrates this<br />

technique.<br />

rand_example.c<br />

#include <br />

#include <br />

int main() {<br />

int i;<br />

printf("RAND_MAX is %u\n", RAND_MAX);<br />

srand(time(0));<br />

}<br />

printf("random values from 0 to RAND_MAX\n");<br />

for(i=0; i < 8; i++)<br />

printf("%d\n", rand());<br />

printf("random values from 1 to 20\n");<br />

for(i=0; i < 8; i++)<br />

printf("%d\n", (rand()%20)+1);<br />

Notice how <strong>the</strong> modulus operator is used to obtain random values from<br />

1 to 20.<br />

reader@<strong>hacking</strong>:~/booksrc $ gcc rand_example.c<br />

reader@<strong>hacking</strong>:~/booksrc $ ./a.out<br />

RAND_MAX is 2147483647<br />

random values from 0 to RAND_MAX<br />

Programming 101

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!