The rand function

May 19, 2011 at 6:15am
Hello, everyone.

This is a sample code of my function, which allocate memory for random char array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdlib.h>
#include <time.h>
unsigned char * separator_generator(unsigned char * len)
{
    /* Variable declaration */
    unsigned char * separator_pointer;
    time_t t;
    int i;

    /* Generating random length */
    srand((unsigned)time(NULL));
    unsigned char separator_len = rand() % 70 + 20;


    /* Allocating memory for separator */
    separator_pointer = malloc(sizeof(char)*separator_len);

    /* Generating separator */
    for (i=0; i<separator_len; i++)
    {
        separator_pointer[i] = rand()%256;
    }

    *len = separator_len;
    return separator_pointer;
}


I use this function here:

1
2
3
4
5
6
7
unsigned char * separator_f;
unsigned char * separator_s;
unsigned char separator_f_len;
unsigned char separator_s_len;

separator_f = separator_generator(&separator_f_len);
separator_s = separator_generator(&separator_s_len);


And the problem...

When i compile program and run it in a console
The separator_f and separator_s has the same length and the same content.

WHY????
Last edited on May 19, 2011 at 6:15am
May 19, 2011 at 6:27am
That's because you seed the PRNG with the same value before generating each set of numbers.
See http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

You should call srand just once at the beginning of your program.
Last edited on May 19, 2011 at 6:28am
May 19, 2011 at 6:39am
Thanks, Athar.
Already, clear up.
Topic archived. No new replies allowed.