The Missing Bit

Using address sanitizer with rust and C libraries

For one of my project, I am writing a mix of Rust and C code. I have to write quite a bit of unsafe Rust to call my C functions.

I had some subbtle memory corruption and I couldn't find the issue.

After a while, I was able to enable the AddressSanitizer, here is how.

If you are not familiar with the Google's AddressSanitizer, it is a set of diagnosis tools, now built into GCC/Clang, that help tracks memory problems.

In C, you can simply use it with the -fsanitize=address compiler and linker flag. But from Rust, this is a bit more complex. The progress is tracker in this issue.

There is an experimental flag -Z sanitizer so you will need rust nighly.

Then there are two gotchas, first, you must build all code with the -fsanitize=address flag, so if you use the cc like me, just add .flag("-fsanitize=address") to your builder.

Then, the second gotcha is that you must run cargo with target, like this:

RUSTFLAGS="-Z sanitizer=address" cargo test --target x86_64-unknown-linux-gnu

This will compile and run the code with the sanitizer. Also ensure you do not have cargo incremental compilation enabled.