Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust ffi pointer does not panic when out of bounds

For some reason, when I run the code below, it does not panic or throw any errors…?

Isn’t this a seg fault?

Why is this happening? How do I check the size of the passed pointer to avoid panics? (without the user having to pass a "size" variable as well)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#[repr(C)]
pub struct MyStruct {
    pub item: u32
    // a bunch of other fields as well
}

#[no_mangle]
pub unsafe extern fn do_something(mut data: *mut MyStruct) {
    println!("{:p}", data);
    data= data.offset(100);
    println!("{:p}", data);
    println!("{}", (*data).item);
    if data.is_null() {
        println!("datais null");
    }
}

After I build, (and generate header using cbindgen) I link and use in a sample program like so:

#include "my_bindings.h"
int main() {
    MyStruct *data = new MyStruct[2];
    do_something(data);
    return 0;
}

This is the output I get:

0x55f0ba739eb0
0x55f0ba73a108
0

>Solution :

An out of bounds access is not necessarily a segmentation fault, it’s just an unidentified behaviour, the data that’s out of bounds may still be a part of your application so the OS won’t kill your application.

Unfortunately this is unsafe code, so rust can’t do anything about it, and you should wrap it in a safer rust container along with the container length (you must pass the length), that panic on out of bounds access, as in the following answer Creating a Vec in Rust from a C array pointer and safely freeing it?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading