Tuesday

Unsafe Rust vectors

Here's the unsafe Rust vectors program that implements a vector Vec template with the <String> data type.
This program demonstrates the use of Vec<String> to store a collection of strings.
The push and pop methods are used to add and remove elements from the vector.
Indexing is used to access specific elements within the vector.
The {:?} format specifier is used to print the value of a variable in a readable format.

This Rust program is unsafe and has out-of-bounds access.
If the index 3 is out of bounds. i.e., if the vector has fewer than four elements, accessing people_names[3] would result in undefined behavior, potentially leading to memory errors or crashes.

To have safe alternative, you can achieve the same functionality using safe Rust constructs. For example, you could use the get() method on the vector to safely access elements, which returns an Option to handle out-of-bounds case.


fn main() {

    let mut people_names : Vec<String> = Vec::new();

    people_names.push("Person_Name_01".to_string());

    people_names.push("Person_Name_02".to_string());

    people_names.push("Person_Name_03".to_string());

    people_names.push("Person_Name_04".to_string());


    people_names.pop();


          // index out of bounds: the len is 3 but the index is 3

    let fourth = &people_names[3];

    println!("Fourth person is {:?}", fourth);

}

No comments:

Unsafe Rust vectors

Here's the unsafe Rust vectors program that implements a vector Vec template with the <String> data type. This program demonstrate...