`black_box` for cargo fuzz

โš“ Rust    ๐Ÿ“… 2026-01-20    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 6      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: `black_box` for cargo fuzz

I am trying to use cargo fuzz run --sanitizer=memory ... to fuzz a function which performs invalid memory access. I don't really care about the result of the function call, I just want to check for invalid memory access.

The problem is that std::hint::black_box does not seem to have the desired effect for this, see `std::hint::black_box` does not work ยท Issue #436 ยท rust-fuzz/cargo-fuzz ยท GitHub, whereas println! does work but I assume it causes quite some overhead.
Here is the example from that GitHub issue:

#![no_main]

use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
    unsafe {
        let a = std::mem::MaybeUninit::<[usize; 4]>::uninit();
        let a = a.assume_init();
        std::hint::black_box(a[2]);
        // // This causes the memory error to be detected
        // println!("{}", a[2]);
    }
});

Are you aware of good alternatives for black_box in this case? I have tried using Copilot suggested alternatives such as writing the result to a AtomicUsize, but that does not seem to help either.

Or is this maybe not actually black_box vs. println!, and rather in both cases invalid memory access occurs but MemorySanitizer is not guaranteed to detect all cases (and somehow the different generated code makes a differences)?

1 post - 1 participant

Read full topic

๐Ÿท๏ธ Rust_feed