Description
This Stack Overflow question points out this relatively-common C idiom (trimmed down to show the interesting bits):
let mut errbuf = [0 as c_char, ..256];
c_function_that_fails(errbuf.as_mut_ptr() as *mut libc::c_char);
CString::new(errbuf.as_ptr(), false);
The questioner wonders about the case where errbuf
is not correctly set and no NUL
bytes occur in the buffer. When we go to use the string, we might merrily walk our way through memory! Since we know the length of errbuf
, we should be able to check that there is a NUL
in the first X bytes and fail otherwise.
While looking to see how Rust handles this case, I found the following spots that could suffer from the same problem:
I propose we add a new constructor to CString
: of_max_len
. This would make sure that a NUL
byte occurs within a certain number of bytes. If it doesn't, we panic!
.
I think we could also make this particular case easier with a constructor like from_slice
, which could be passed the slice which would implicitly know its length.
I'm more than welcome to feedback of all kinds!