Iterating a slice of *const c_char corruptioin


I came across a strange behavior which surprised me. Using the iterator api of a slice of *const c_char causes some memory corruption. The context is handling program arguments in a no_std program:


use core::ffi::*;

extern "C" {
    pub fn printf(fmt: *const c_char, ...) -> c_int;

pub extern "C" fn main(argc: c_int, argv: *const *const c_char) -> c_int {
    unsafe {
        let args = core::slice::from_raw_parts(argv, argc as _);
        for i in 0..argc { // this works
            printf("%s\n\0".as_ptr() as _, args[i as usize]); 
        for arg in args {  // corruption here
            printf("%s\n\0".as_ptr() as _, arg);

fn ph(_: &core::panic::PanicInfo) -> ! {
    loop {}

Is it a bug in the code above? Or are my assumptions wrong?

P.S. To build you need to change your Cargo.toml:

panic = "abort"
# similarly change profile.release

And you might need to link libc in a file depending on your rust version:

fn main() {

I believe arg is a reference to the slice element containing the C pointer, so you need to pass *arg to pass the C pointer.

1 Like

Yes indeed, dereferencing arg fixes the issue.
Thank you

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.