4

Trying to use the JACK-AUDIO-CONNECTION-KIT from Rust (documentation), I run into problems calling

jack_client_t* jack_client_open (   const char *    client_name,
                                    jack_options_t  options,
                                    jack_status_t *     status,
                                    ... )   

In Rust I use

#[link(name = "jack")]
extern "C" {
    pub fn jack_client_open(name: *const libc::c_char,
                        options: JackOptions,
                        status: &JackStatus)
                        -> *mut JackClientT;
}

(complete code)

When I use a name with four characters it works, e.g.

let name = CString::new("yass").unwrap().as_ptr();

but if I use 5 or more characters it doesn't work. In the JACK docs linked to above, it says that the name can be at most int jack_client_name_size() characters long, which is 64 in my case. Why does this happen?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
poidl
  • 433
  • 1
  • 4
  • 9

1 Answers1

6

let name = CString::new("yass").unwrap().as_ptr(); allocates a string, gets a pointer to it... then throws away the string, so you get a use-after-free. Don't do this. Write let name = CString::new("yass").unwrap();, then use name.as_ptr(). See also CStr::as_ptr and this RFC proposal.

Any suggestions to improve the documentation would be welcome.

malbarbo
  • 10,717
  • 1
  • 42
  • 57
Eli Friedman
  • 2,343
  • 1
  • 13
  • 11
  • Makes sense now, thanks! The warning in the docs is good. From the RFC proposal it seems many beginners (like me) struggle with this. Would it make sense to "encourage" users to use a naming convention for raw pointers, i.e. issue a warning if raw pointers do not end in "*_ptr". Maybe in the long run that would increase alertness regarding correct memory management, and would prompt people to not rely on the compiler to error if something is wrong. More advance people could disable the warning. – poidl Jun 25 '16 at 00:36