Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider using `&T` for returning pointers into the buffer of C wrapper types like CString #382

Closed
huonw opened this Issue Oct 9, 2014 · 4 comments

Comments

Projects
None yet
4 participants
@huonw
Copy link
Member

huonw commented Oct 9, 2014

Code like

let p = "foo".to_c_str().as_ptr();

println!("first c_char is {}", unsafe {*p});

is unsafe because the CString is deallocated at the end of the initializer for p leaving that pointer dangling and hence the dereference inside the println! is incorrect.

as_ptr is currently returning a *const i8, which, due to being a raw pointer, does not have any compiler-enforced connection to its parent object, meaning it can become dangling as demonstrated above.

We could address the worse examples of this by making it instead return &i8 (connected to self), and since &i8 implicitly coerces to *const i8 I expect that most code will not have to change. However, I don't know of any other place that uses a & as a pointer-to-a-buffer (using it as a pointer to a single element is common, of course) so this would be a new 'feature'.

Thoughts?

@aturon

This comment has been minimized.

Copy link
Member

aturon commented Oct 9, 2014

👍

In general, the C wrapper types could use a rethink before stabilization (see this issue for example).

@huonw are you interested in working together on a revised design? I had this on the stabilization schedule for November.

@aturon

This comment has been minimized.

Copy link
Member

aturon commented Oct 9, 2014

@ben0x539

This comment has been minimized.

Copy link

ben0x539 commented Oct 13, 2014

Doesn't this suggest the wrong thing in terms of aliasing? CString also has as_mut_ptr().

@alexcrichton

This comment has been minimized.

Copy link
Member

alexcrichton commented Feb 11, 2016

These types and signatures have since been stabilized, so closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.