Rust

Rust

Made by DeepSource

Found redundant unsafe operation: libc::strlen RS-W1098

Anti-pattern
Minor

The length of CStrings may be calculated with .as_bytes().len(), which is safe and performant, as compared to libc::strlen, which is an unsafe operation.

The following alternatives are preferred:

  • For CStrings, .as_bytes().len()
  • For CStrs, .to_bytes().len()

Bad practice

let my_string = CString::new("foo").expect("CString::new failed");
let length = unsafe {
        libc::strlen(my_string.as_ptr())
    };

Recommended

let my_string = CString::new("foo").expect("CString::new failed");
let length = my_string.as_bytes().len();