Skip to content

Memory safety issue in CStringIter with invalid pointers #36

@yaokunzhang

Description

@yaokunzhang

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions