在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
isNULL
, and the first loop of yourfor
invokes undefined behavior: you dereferences theNULL
pointer.