Zig: lots of valgrind warnings from adding a seemingly unrelated line of code

Created on 13 Mar 2019  路  2Comments  路  Source: ziglang/zig

const std = @import("std");

const Lel = struct {
    rnd: *std.rand.Random,

    fn init(rnd: *std.rand.Random) Lel {
        return Lel{ .rnd = rnd };
    }
};

pub fn main() anyerror!void {
    const allocator = std.heap.c_allocator;

    var buf: [8]u8 = undefined;
    try std.os.getRandomBytes(buf[0..]);
    std.debug.warn("random bytes: {} {} {} {} {} {} {} {}\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]);
    var default_prng = std.rand.DefaultPrng.init(std.mem.readIntSliceLittle(u64, buf[0..]));
    var rnd = default_prng.random;
    std.debug.warn("{}\n", rnd.uintLessThan(u8, 10));

    const lel = Lel.init(&rnd);
}

Build with zig build-exe main.zig --library c and run valgrind ./main to get lots of errors. Then comment out const lel = Lel.init(&rnd); and build and valgrind again, no errors.

zig version: 0.3.0+d495dcc3

duplicate

Most helpful comment

This is actually #591. Can't believe I thought it was a Valgrind bug for a hot minute! Sorry to any Valgrind developers reading this.

-    var rnd = default_prng.random;
+    const rnd = &default_prng.random;

All 2 comments

I can reproduce this with 85d0f0d45bf1529db8965b8176f8021d1ca27534 and Valgrind 3.14 on x86_64-linux-gnu and x86_64-linux-musl. Some observations:

  • The allocator line is not necessary to reproduce the problem, but --library c is.
  • Replacing the allocator line with var trash = std.heap.DirectAllocator.init(); makes the valgrind errors go away, even when linking with --library c.
  • The valgrind errors still appear when using --disable-valgrind.

This is either a bug in Zig or in Valgrind, and based on the fact that it still happens with --disable-valgrind makes me lean towards it being a Valgrind bug.

==23944== Memcheck, a memory error detector
==23944== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==23944== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==23944== Command: ./test
==23944== 
random bytes: 170 175 20 182 157 21 28 248
==23944== Conditional jump or move depends on uninitialised value(s)
==23944==    at 0x2252B7: std.rand.Random.uintLessThan (rand.zig:95)
==23944==    by 0x224D39: main.0 (test.zig:19)
==23944==    by 0x224A46: std.special.callMain (bootstrap.zig:122)
==23944==    by 0x224A46: std.special.callMainWithArgs (bootstrap.zig:94)
==23944==    by 0x224A46: main (bootstrap.zig:101)

This is actually #591. Can't believe I thought it was a Valgrind bug for a hot minute! Sorry to any Valgrind developers reading this.

-    var rnd = default_prng.random;
+    const rnd = &default_prng.random;
Was this page helpful?
0 / 5 - 0 ratings

Related issues

andrewrk picture andrewrk  路  3Comments

andrewrk picture andrewrk  路  3Comments

zimmi picture zimmi  路  3Comments

komuw picture komuw  路  3Comments

S0urc3C0de picture S0urc3C0de  路  3Comments