How to avoid "use of possibly uninitialized data"

I have a DLL written in C and a main program also written in C to call the DLL. Recently I am translating the main program from C to rust, but keep the DLL unchanged. Today I encounter the following issue.

In the main program, the following C function exported by the DLL is called:

int php_sys_stat_ex(const char *path, zend_stat_t *buf, int lstat);

Bindgen translates this declaration into rust:

extern "C" {
     pub fn php_sys_stat_ex(
         path: *const ::std::os::raw::c_char,
         buf: *mut zend_stat_t,
         lstat: ::std::os::raw::c_int,
     ) -> ::std::os::raw::c_int;

In this function the second argument is a pointer to a data structure, which is filled according to the information supplied by the first argument. So the initialization of the data structure *buf is done in this function. I tried to translate the statements calling this function into rust, but I saw the following error:

Then my question is: How could I avoid this error? The initialization is supposed to be done in the function I want to call, but the rust compiler stops me calling the function because of "use of possibly uninitialized data"!

If you don't want to initialize the var with dummy data, use std::mem::MaybeUninit - Rust
Calling as_mut_ptr

Thank you! Can you give more detailed guide? I am a newcomer to rust.

MaybeUninit is not about dummy data. It's about uninitialized data, and touching it's content before initialization is UB means you're violating the language's rule.

So basically the usage could look like this

let mut sb = MaybeUninit<zend_stat_t>::uninit();
if php_sys_stat_ex(document_root.as_ptr() as *const i8, sb.as_mut_ptr(), 0) != 0 {
// If php_sys_stat_ex returning success
// guarantees `sb` got initialized, then this is safe:
let sb = unsafe { sb.assume_init() }:

// use and/or return `sb`

To avoid UB, you must make sure that php_sys_stat_ex is okay with being passed a pointer to uninitialized memory and that it properly initializes it.

1 Like

Whopse, my phrasing was off.
I meant that as MaybeUninit or dummy value

Thank you so much!