Skip to content

CString's as_ptr is easy to get very wrong #16630

Description

@spaolacci

Whilst the documentation explicitly mentions the situation, precise scope is easy to get wrong.

// .as_ptr returns an internal pointer into the CString, and may be invalidated when the                                                                                        
// CString falls out of scope (the destructor will run, freeing the allocation if there is                                                                                      
// one).                                                                                                                                                                        
let s = "foo";                                                                                                                                                                  
let s1 = s.to_c_str(); // Ok.                                                                                                                                          
let s2 = s.to_c_str().as_ptr(); // Oops.                                                                                                                                        
//         ^~~~ tmp CString falls out of scope.                                                                                                                                 

let (c1, c2) = unsafe{ (*s1.as_ptr(), *s2) };                                                                                                                                   
println!("{}, {}", c1, c2); //  Prints `102, 0'

The same pattern is even easier to overlook in e.g libc::open(filename.to_c_str().as_ptr(), ...).

String's with_c_str should probably be preferred (or documented as preferred).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions