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

why does value allocated in stack didn't result in double free pointer?

Please tell me why didn’t result in double free pointer that the value is allocated in stack? Thanks.

#[test]
fn read_value_that_allocated_in_stack_is_no_problem() {
    let origin = Value(1);
    let copied = unsafe { std::ptr::read(&origin) };

    assert_eq!(copied, Value(1));
    assert_eq!(copied, origin);
}

/// test failed as expected: double free detected
#[test]
fn read_value_that_allocated_in_heap_will_result_in_double_free_problem() {
    let origin = Box::new(Value(1));
    let copied = unsafe { std::ptr::read(&origin) };

    assert_eq!(copied, Box::new(Value(1)));
    assert_eq!(copied, origin);
}


#[derive(Debug, PartialEq)]
struct Value<T>(T);

>Solution :

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

The unsafe method you are using just creates a bitwise copy of the referenced value. When you do this with a Box, it’s not okay but for something like your Value struct containing an integer, it is okay to make the copy as Drop of integers has no side effects while drop of Box accesses global allocator and changes the state.

If you do not understand any term I used for this explanation, try to search it or ask in the comments.

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