I'm at my wits end. This trivial code gives me Segfault, what could be possibly wrong??
struct random_data *qq;
qq = calloc(50, sizeof(struct random_data));
srandom_r(time(NULL), qq);
Now if I change it like this, it works:
struct random_data qq;
srandom_r(time(NULL), &qq);
I must be a total moron, but I can't grasp it. Please, help.
Update: calloc returns a valid pointer
(uint64_t) 1aa5010
However, &qq represents the pointer
(uint64_t) 7fffbb428090
and that's the difference, but it's unclear why srandom_r fails to execute. I try at Linux 2.6.32-44-server #98-Ubuntu
it seems like most answers never actually tried to run your code. here's a very minimalistic program, that indeed exhibits your problem:
valgrind doesn't show much apart from an illegal memory access:
now when looking at the
random_data
struct, you will find that it contains a pointer to a state-buffer:obviously all those pointers will be NULL if you allocate with
calloc()
, andsrandom_r
doesn't really like that. you can help it be manually allocating an array of state values and assign it to therandom_data
struct usinginitstate_r
. sinceinitstate_r
already takes aseed
, you don't need to callsrandom_r
anymore (but you can if you want to):