用rand()替换/ dev / urandom

在ubuntu上,程序使用

FILE *randomSource = fopen("/dev/urandom", "rb");
int byteCount = fread(buf, sizeof(unsigned char), num, randomSource);

我想用stdlib中的rand()代替它,因为我需要在没有/ dev / urandom的环境中使用它。 我已经尝试过这种方式:

buf = malloc (num);
int i;

for (i = 0; i < num; i++)
{
  buf[i] = rand ();
}

但是显然这并不等效,因为程序会失败。结果应该是n个随机字节,其中buf指向第一个。

评论
盛水冬
盛水冬

You don't explain how does the program fails. Read more about rand and consider seeding your PRNG.

Also malloc can fail, and you don't test against that. If malloc fails, buf is NULL, and the first loop of your for invokes undefined behavior: you dereferences the NULL pointer.

点赞
评论