Does anyone actually length-check CStr::from_ptr?

2026-11-24来源 Rust Users ForumEnglish

I was doing some FFI wrapping and saw this note in the CStr::from_ptr documentation (CStr in std::ffi - Rust):

The nul terminator must be within isize::MAX from ptr

Because malloc and objects in C generally use size_t which is equivalent to usize::MAX, it would seem like we need to check this constraint right? For example on a 32-bit system we might have a 3GB string which is more than CStr can handle.

Looking through various projects and the standard library I can't find anyone checking this. The SAFETY mentions seem to be things like this:

 // SAFETY: Just checked that the pointer is not NULL, and arguments // are otherwise guaranteed to be valid C strings. let cstr = unsafe { CStr::from_ptr(ptr) }; vec.push(OsStringExt::from_vec(cstr.to_bytes().to_vec())); 

Right now it does do a sanity check at debug that should catch this issue:

 // Chance at catching some UB at runtime with debug builds. debug_assert!(!bytes.is_empty() && bytes[bytes.len() - 1] == 0); 

Though the documentation also implies this will be removed eventually?

Note: This operation is intended to be a 0-cost cast but it is currently implemented with an up-front calculation of the length of the string. This is not guaranteed to always be the case.

I do wonder what I'm supposed to do here outside add my own check that a C string is under isize::MAX. But there's a lot of code out there that doesn't do this...

3 posts - 3 participants

Read full topic

原文:https://www.a8q9.cn/en/article/does-anyone-actually-length-check-cstr-from-ptr-e02b38.html

相关文章