tinyrlibc icon indicating copy to clipboard operation
tinyrlibc copied to clipboard

Memory safety issue in CStringIter with invalid pointers

Open yaokunzhang opened this issue 3 months ago • 1 comments

Description:

Hello! My static analyzer has identified a potential memory safety issue in the tinyrlibc crate that I'd like to report.

Problem:

The CStringIter::new method in src/ctype.rs accepts raw pointers without validation. While the documentation mentions "behaviour is undefined if the string is not null-terminated," users can easily pass dangling pointers or invalid addresses through safe APIs, leading to undefined behavior when iterating.

Reproduction:


use tinyrlibc::{CStringIter, CChar};

fn main() {
    let invalid_ptr: *const CChar = {
        let temp_string = std::string::String::from("Hello\0");
        temp_string.as_ptr()
    }; // temp_string is dropped here, making the pointer dangling
    
    let iter = CStringIter::new(invalid_ptr);
    
    for (i, c) in iter.enumerate() {
        println!("char {}: {} ({})", i, c as char, c);
        if i > 10 { break; }
    }
}

Suggestions:

  • Consider making the constructor unsafe to make the preconditions explicit
  • Improve documentation with safety requirements and examples

yaokunzhang avatar Oct 01 '25 04:10 yaokunzhang