I\'m trying to learn more about FFI in Rust and linking with C libraries, specifically libc
. While on my "quest", I came across the following problem.
The standard library defines a couple of types and functions to deal with initialization. They are generic, so they can be used to initialize values of any type.
Modern Rust suggests using MaybeUninit in most cases. Applied to your case, it would look something like:
use std::mem::MaybeUninit;
let mut new_action: libc::sigaction = MaybeUninit::zeroed().assume_init();
let mut old_action: libc::sigaction = MaybeUninit::zeroed().assume_init();
MaybeUninit
was stabilized in Rust 1.36. Before that, you could use std::mem::uninitialized(), which gives you an uninitialized value. LLVM will consider the contents to be undefined, and will perform aggressive optimizations based on this. You must initialize any value before it's read.
More appropriate to your case, there's std::mem::zeroed(), which gives you a value whose storage is filled with zeroes. This function is unsafe
because such a value is not necessarily legal for all types. zeroed()
is appropriate for "plain old data" (POD) types. Applied to your case, it would look something like:
use std::mem;
let mut new_action: libc::sigaction = mem::zeroed();
let mut old_action: libc::sigaction = mem::zeroed();
How about using mem::zeroed? The docs even say:
This is useful for FFI functions sometimes, but should generally be avoided.