Skip to content

std::hint::black_box does not work? #436

Description

@Marcono1234

Problem

It seems using black_box in fuzz targets does not have the desired effect, when it is used invalid memory access is not detected when running with cargo fuzz run --sanitizer=memory ....

Therefore (assuming I did not make a mistake in my test setup) I would be useful to:

  • mention prominently in the documentation that black_box should not be used for fuzz tests
  • mention alternatives

Reproduction steps

Version information:

Ubuntu 24.04
Linux Kernel 6.6.87.2-microsoft-standard-WSL2
cargo 1.94.0-nightly (6d1bd93c4 2026-01-10)
cargo-fuzz 0.13.1

Steps:

  1. mkdir fuzztest
  2. cd fuzztest
  3. cargo init --lib
  4. cargo fuzz init
  5. Edit fuzz/fuzz_targets/fuzz_target_1.rs:
    #![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]);
        }
    });
  6. cargo +nightly fuzz run --sanitizer=memory fuzz_target_1 -- -runs=5
    ❌ Bug: No memory error is detected
  7. Change fuzz_target_1.rs:
              let a = a.assume_init();
    -         std::hint::black_box(a[2]);
    +         println!("{}", a[2]);
          }
  8. cargo +nightly fuzz run --sanitizer=memory fuzz_target_1 -- -runs=5
    ℹ️ As expected: The memory error is detected

Notes:

  • While this is a quite contrived example, I had originally noticed this when fuzzing a compression library where it made a difference as well whether I passed the result to black_box vs println!.
  • For this simple example using cargo fuzz run ... --dev helps; for the actual compression library I am fuzzing it does not seem to help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions