Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std.rand.DefaultPrng causes memory corruption #9080

Closed
samhattangady opened this issue Jun 11, 2021 · 2 comments
Closed

std.rand.DefaultPrng causes memory corruption #9080

samhattangady opened this issue Jun 11, 2021 · 2 comments

Comments

@samhattangady
Copy link
Sponsor Contributor

I am storing a randomiser variable of type std.rand.Random in a struct. Whenever I use that randomiser to get a random number, it corrupts memory after it in the struct.

const std = @import("std");

const RNG = struct {
    const Self = @This();
    num1: u32 = 42,
    randomiser: std.rand.Random,
    num2: u32 = 42,

    pub fn init() Self {
        return Self{
            .randomiser = std.rand.DefaultPrng.init(0).random,
        };
    }
};

pub fn main() anyerror!void {
    var rng = RNG.init();
    std.debug.print("{d}, {d}\n", .{rng.num1, rng.num2});
    _ = rng.randomiser.int(u32);
    std.debug.print("{d}, {d}\n", .{rng.num1, rng.num2});
}

Output:

42, 42
42, 17465386

I am able to get around this by changing the type stored in the struct to std.rand.DefaultPrng, so I am not sure whether I am making some mistake by storing a std.rand.Random, or whether this is actually a bug. I also tried this with std.rand.DefaultCsprng, and while there was no memory corruption in that case, it did lead to a segmentation fault may mean that there is a bug there as well.

I am using zig version zig-windows-x86_64-0.9.0-dev.71+138afd5cb

Thanks,

@Vexu
Copy link
Member

Vexu commented Jun 11, 2021

You are taking the interface out of the implementation and causing invalid pointer dereferences, this is a known footgun and will be fixed by #7769.

@Vexu Vexu closed this as completed Jun 11, 2021
@samhattangady
Copy link
Sponsor Contributor Author

Good to note. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants