0

I'm building a Rust to python FFI using libc and I am encountering a "invalid pointer" error. On the python side of things, I'm doing:

print(CDLL("./libshared.so").print_stuff(c_char_p("test".encode("utf-8")), 4))

...which does print the intended value but then errors with:

munmap_chunk(): invalid pointer
Fatal Python error: Aborted

Current thread 0x00007eff895ee740 (most recent call first):
  File <FILE>, line 7 in <module>
Aborted

I'm assuming that this is occurring because a pointer has been freed by Rust, but C does not know that. Hence, I'm trying to free this pointer by using libc::free. In order to do this, I need to somehow convert the String type to *mut _ that the method can receive as an argument. I've tried coersion and transmutation, but neither would be possible. Below is my Rust code.

unsafe { 
        let string = String::from_raw_parts(array as *mut u8, length, 5);
        println!("{:?}", string);
        libc::free(/* variable string somehow converted to type c_void **/);
};
DevComp
  • 11
  • 7
  • The rule is: if you create it in C, free it in C; create in Rust? free in Rust. I'm not sure why you're using `libc` directly anyways. Are you familiar with the `pyo3` crate? It allows you to seamlessly write Rust code usable from Python and vice versa. – Maximilian Burszley Dec 15 '22 at 13:55
  • @MaximilianBurszley I am familiar with `pyo3`, but the main reason I'm doing this is for future scalability. Soon, I'll need to be able to have a standardized medium to call Rust code from languages other than Python too (for example, Go). – DevComp Dec 15 '22 at 14:00
  • There's not enough context in your question to help you further (what is `array`? what function is exposed for FFI and how?) and I don't see the purpose of what you're trying to do. Good luck – Maximilian Burszley Dec 15 '22 at 14:01
  • 1
    Also, you're right -- this makes way more sense now this way. I was able to deallocate the pointer in Rust and all goes well now. Thanks! – DevComp Dec 15 '22 at 14:02
  • Just for the record, "thar be dragons" even when freeing a pointer across a DLL boundary, let alone a _language_ boundary. Even if you _can_ do this, that doesn't mean you _should_ if you can avoid it. – Kevin Anderson Dec 15 '22 at 14:42
  • Well then, should I just tell Rust to forget the pointer? – DevComp Dec 15 '22 at 15:31

0 Answers0