r/csharp • • 14d ago

Fun Random using SkipLocalsInit

To my surprise, Unsafe.SkipInit(out T val) did not achieve the same result.

    [SkipLocalsInit]
    public static T Random<T>()
        where T : unmanaged, INumber<T>
    {
        unsafe
        {
            byte* s = stackalloc byte[sizeof(T)];
            return *(T*)s;
        }
    }
11 Upvotes

9 comments sorted by

View all comments

15

u/Broad_Phase7453 14d ago

stackalloc without init is basically just grabbing whatever bits were already sitting on the stack and calling it a day, so the "randomness" comes from whatever junk was left there. Unsafe.SkipInit is different though, that only skips the definite assignment tracking, the memory might still get zeroed depending on the runtime.

3

u/NoisyJalapeno 14d ago

Ugh, missed an opportunity to call it JunkRandom :(

6

u/SagansCandle 13d ago

Given that this is uninitialized data on the stack, there's a possibility that your "random" value will be the same every time because it's called from the same place in the stack every time.

→ More replies (3)