Skip to content

CString should have a "within max length" constructor #20475

Closed
@shepmaster

Description

@shepmaster

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-acceptedCategory: A feature request that has been accepted pending implementation.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions