Guidance on how to pass null for a pointer to a pointer

⚓ Rust    📅 2025-08-28    👤 surdeus    👁️ 10      

surdeus

Warning

This post was published 96 days ago. The information described in this article may have changed.

I've not done much rust so i've jumped off at the deep end to by doing some FFI C calls. I'm unsure of the correct way to make one of my calls.

I have a C function which has the signature something like
void f(char** buf);
In C you can do these two calls.

char* buf;
f(&buf); // Function returns a pointer to something and does something
f(NULL); // Function does something but doesn't return a pointer.
  1. What would be the correct signature for this function in rust? I hope I don't embarrass my self but I have this. fn f(buf : &*mut libc::c_void);?
  2. How should I do the two different calls?
let mut buf : [i8; 5] = [1,2,3,4,5];
unsafe{f(& buf.as_mut_ptr());}  // seems to work but I'm not entirely sure it is correct.

unsafe{f(& *ptr::null_mut());}   // I get the warning 'this code causes undefined behavior when executed'

8 posts - 6 participants

Read full topic

🏷️ Rust_feed