Avoid use of uninitialized value passing pointer to C FFI?

I'm trying to use libc's lstat, and in the normal C convention, it takes a pointer to an existing structure which will be filled on success. Naively, we could try:

    let mut s: stat;
    unsafe {
        lstat(path, &mut s);
    }

Of course, since s hasn't been initialized, this produces an error. You might say, "OK, so just initialize s to something to make the compiler happy." Unfortunately, the definition of the stat type is as follows:

pub struct stat {
    pub st_dev: dev_t,
    pub st_ino: ino_t,
    pub st_nlink: nlink_t,
    pub st_mode: mode_t,
    pub st_uid: uid_t,
    pub st_gid: gid_t,
    pub st_rdev: dev_t,
    pub st_size: off_t,
    pub st_blksize: blksize_t,
    pub st_blocks: blkcnt_t,
    pub st_atime: time_t,
    pub st_atime_nsec: c_long,
    pub st_mtime: time_t,
    pub st_mtime_nsec: c_long,
    pub st_ctime: time_t,
    pub st_ctime_nsec: c_long,
    // some fields omitted
}

Suffice it to say, manually constructing an instance of that type would be a big pain. Is there any other way to accomplish this? heap::allocate would normally be an (albeit slow) option, but this is for a no_std crate, so that's off the table.

1 Like

mem::uninitialized or mem::zeroed is typically used.

3 Likes

That's perfect; thanks!