Hi! I wrote a software, but isn't works well. I found the problematic point and made a short example: Rust Playground
Shouldn't the compiler stop with lifetime error?
Hi! I wrote a software, but isn't works well. I found the problematic point and made a short example: Rust Playground
Shouldn't the compiler stop with lifetime error?
*const c_char
doesn't have a (Rust) lifetime (one of those '_
things).
unsafe
means it's on you, the programmer, to ensure everything is valid -- for example, that the pointed-to memory hasn't been deallocated. You opted out of the compiler protecting you.
I would agree that this documentation should be improved. " called with a pointer that was earlier obtained by calling CString::into_raw
" is necessary but not sufficient.
The focus isn't on fn printval() and CString::from_raw. It is only a debugfunc in playground.
My original software, I used for mount in libc - Rust
The focus is on the main() part.
If I use inner variable, the contents of "moptions" ptr will be random.
If I used outer variable, the contents of "moptions" ptr is OK.
There is nothing unsafe in the main function, only CString and a pointer for this CString.
It's best to be more precise in your initial question.
Raw pointers don't have the notion of lifetime, and as long as you don't use what they're pointing at, it doesn't matter. You can only use the data a raw pointer is pointing at in an unsafe block or function. That's what @quinedot said about the programmer's responsibility.
EDIT: You should have a loot at Miri, in the Tools section (your playground link). It's a program that executes your code and makes more thorough checks about memory aliases than the compiler is able to. You'll see that your code triggers an error with Miri - unfortunately, understanding the messages takes some getting-used-to. If you're planning on using unsafe code, I'd strongly advise you to include Miri in your validations, even if it's a little slower.
You're running into the dangerous mix of unsafe pointers and automatic destruction:
Many thanks for this information. I dont know this before. Possible this should better, if the raw pointer will be in "unsafe" extension.
As I wrote, it was bad that in my original software the mount option didn't go through (instead random memory value), and I had to look for the reason why. Because of "unhadled" lifetime in safe part of code.
Using unsafe code isn't trivial when you must handle lifetimes or allocate / deallocate objects. As @kornel pointed out above, a common trap is accessing data that has already been deallocated because it had reached its end of life or has been moved.
Have you read the Rustonomicon? It's a good starting point. There's a section on Foreign Function Interface.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.