Local Random Number Generator sometimes core dumps2

From your init function, you are returning a struct instance that contains a reference to the prng state (via rand, which contains a pointer to prng). This prng state only exists on the init stack frame; as soon as you return and call a different function, the memory that rand points to will be overwritten by something else, which will likely result in a segfault. If you get different results with different optimization modes it’s likely just a side effect of them optimizing function calls differently.

Structs that contain pointers that reference themselves (in this case the rand field pointing to the prng field) can be difficult to set up and are very prone to problems if they are copied around. I would suggest one of the following alternate designs:

  • Remove the prng field and instead take a std.Random as an argument to init. That way, the caller has full control both over the RNGs lifetime and the RNG implementation itself.
  • Remove the rand field, and only store prng. When you later want the std.Random interface, you have to get it via what.prng.random().
3 Likes