wen
wen

Reputation: 3848

Writing a Rust test which expects a segfault

I'd like to write a test in Rust where the expected behaviour of the #[test] function is to segfault. Is this possible?

Upvotes: 2

Views: 471

Answers (2)

Lou Garczynski
Lou Garczynski

Reputation: 635

First, I'd like to point out that the only sure way to segfault that I am aware of is to send the SIGSEGV signal to your own process, possibly using the "raise" function or a rust equivalent.

Dereferencing a pointer to unallocated memory or a null pointer doesn't actually guarantee segfault, though it will on most modern platforms.

The simplest way to check for a segfault is to fork your program (possibly using the nix crate). Once done, execute the function that should make you segfault on the child process, while the parent process waits.

After waiting a sufficient amount of time (any more than a few hundred milliseconds is overkill), check that the child thread is dead. To do that, simply kill it, and an error should be raised if it's already dead.

Upvotes: 3

Boiethios
Boiethios

Reputation: 42769

The only correct way to test this is, in my opinion, pretty heavy. In the test, I would run a static analyser that can detect this possible undefined behavior, and verify that this very issue is still there.

I am not aware of a Rust crate that does a static analysis, though, so I guess that you would depend on an extern tool using the C ABI.

Upvotes: 1

Related Questions